473,837 Members | 1,888 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

eval to dict problems NEWB going crazy !

Hi,

I have a text file called a.txt:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]

I read it using this:

filAnsMorph = codecs.open('a. txt', 'r', 'utf-8') # Initialise input
file
dicAnsMorph = {}
for line in filAnsMorph:
if line[0] != '#': # Get rid of comment lines
x = eval(line)
dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is
value

But it crashes every time on x = eval(line). Why is this? If I change
a.txt to:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

it works fine. Why doesn't it work with multiple lines? it's driving me
crazy!

Thanks,
Matthew

Jul 6 '06 #1
15 3675
manstey wrote:
Hi,

I have a text file called a.txt:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]

I read it using this:

filAnsMorph = codecs.open('a. txt', 'r', 'utf-8') # Initialise input
file
dicAnsMorph = {}
for line in filAnsMorph:
if line[0] != '#': # Get rid of comment lines
x = eval(line)
dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is
value

But it crashes every time on x = eval(line). Why is this? If I change
a.txt to:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

it works fine. Why doesn't it work with multiple lines? it's driving me
crazy!
try with:
x = eval(line.strip ('\n'))
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 6 '06 #2
That doesn't work. I just get an error:

x = eval(line.strip ('\n'))
File "<string>", line 1
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

SyntaxError: unexpected EOF while parsing
any other ideas?

Bruno Desthuilliers wrote:
manstey wrote:
Hi,

I have a text file called a.txt:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]

I read it using this:

filAnsMorph = codecs.open('a. txt', 'r', 'utf-8') # Initialise input
file
dicAnsMorph = {}
for line in filAnsMorph:
if line[0] != '#': # Get rid of comment lines
x = eval(line)
dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is
value

But it crashes every time on x = eval(line). Why is this? If I change
a.txt to:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

it works fine. Why doesn't it work with multiple lines? it's driving me
crazy!

try with:
x = eval(line.strip ('\n'))
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 6 '06 #3
manstey wrote:
That doesn't work. I just get an error:

x = eval(line.strip ('\n'))
File "<string>", line 1
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

SyntaxError: unexpected EOF while parsing
is the last line of your file empty ??

what with

for line in filAnsMorph:
# remove any trailing and leading whitespace includes removing \n
line = line.strip()
# Get rid of comment lines
if line.startswith ('#'):
continue
# Get rid of blank line
if line == '':
continue
#do the job
x = eval(line)
NB by default strip() removes leading and trailing characters from the target
string. with whitspace defined as whitespace = '\t\n\x0b\x0c\r '

Eric
Jul 6 '06 #4
"manstey" <ma*****@csu.ed u.auwrote:
That doesn't work. I just get an error:

x = eval(line.strip ('\n'))
File "<string>", line 1
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

SyntaxError: unexpected EOF while parsing

any other ideas?
hint 1:
>>eval("[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]\n")
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
>>eval("[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]")
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

hint 2:
>>eval("")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0

^
SyntaxError: unexpected EOF while parsing
>>eval("\n")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1

^
SyntaxError: unexpected EOF while parsing

hint 3: adding a "print" statement *before* the offending line is often a good way
to figure out why something's not working. "repr()" is also a useful thing:

if line[0] != '#': # Get rid of comment lines
print repr(line) # DEBUG: let's see what we're trying to evaluate
x = eval(line)
dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is

</F>

Jul 6 '06 #5
manstey schreef:
Hi,

I have a text file called a.txt:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]

I read it using this:

filAnsMorph = codecs.open('a. txt', 'r', 'utf-8') # Initialise input
file
dicAnsMorph = {}
for line in filAnsMorph:
if line[0] != '#': # Get rid of comment lines
x = eval(line)
dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is
value

But it crashes every time on x = eval(line). Why is this? If I change
a.txt to:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]

it works fine. Why doesn't it work with multiple lines? it's driving me
crazy!
It looks like it's because of the trailing newline. When you read a file
like that, the newline at the end of each line is still in line. You can
strip it e.g. with rstrip, like so:

x = eval(line.rstri p('\n'))

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Jul 6 '06 #6
hint 1:

hint 1b:
>>eval("[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]")
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
>>eval("[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]\n")
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
>>eval("[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]\r\n")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
^
SyntaxError: invalid syntax

</F>

Jul 6 '06 #7
On Thu, 06 Jul 2006 03:34:32 -0700, manstey wrote:
Hi,

I have a text file called a.txt:

# comments
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]

I read it using this:

filAnsMorph = codecs.open('a. txt', 'r', 'utf-8') # Initialise input
file
dicAnsMorph = {}
for line in filAnsMorph:
if line[0] != '#': # Get rid of comment lines
x = eval(line)
dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is
value

But it crashes every time on x = eval(line). Why is this?
Some people have incorrectly suggested the solution is to remove the
newline from the end of the line. Others have already pointed out one
possible solution.

I'd like to ask, why are you using eval in the first place?

The problem with eval is that it is simultaneously too finicky and too
powerful. It is finicky -- it has problems with lines ending with a
carriage return, empty lines, and probably other things. But it is also
too powerful. Your program wants a specific piece of data, but eval
will accept any string which is a valid Python expression. eval is quite
capable of giving you a dictionary, or an int, or just about anything --
and, depending on your code, you might not find out for a long time,
leading to hard-to-debug bugs.

Is your data under your control? Could some malicious person inject data
into your file a.txt? If so, you should be aware of the security
implications:

# comment
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
# line injected by a malicious user
"__import__('os ').system('echo if I were bad I could do worse')"
[('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]

Now, if the malicious user can only damage their own system, maybe you
don't care -- but the security hole is there. Are you sure that no
malicious third party, given *only* write permission to the file a.txt,
could compromise your entire system?

Personally, I would never use eval on any string I didn't write myself. If
I was thinking about evaluating a user-string, I would always write a
function to parse the string and accept only the specific sort of data I
expected. In your case, a quick-and-dirty untested function might be:

def parse(s):
"""Parse string s, and return a two-item list like this:

[tuple(string, integer), tuple(string, dict(string: string)]
"""

def parse_tuple(s):
"""Parse a tuple with two items exactly."""
s = s.strip()
assert s.startswith("( ")
assert s.endswith(")")
a, b = s[1:-1].split(",")
return (a.strip(), b.strip())

def parse_dict(s):
"""Parse a dict with two items exactly."""
s = s.strip()
assert s.startswith("{ ")
assert s.endswith("}")
a, b = s[1:-1].split(",")
key1, value1 = a.strip().split (":")
key2, value2 = b.strip().split (":")
return {key1.strip(): value1.strip(), key2.strip(): value2.strip()}

def parse_list(s):
"""Parse a list with two items exactly."""
s = s.strip()
assert s.startswith("[")
assert s.endswith("]")
a, b = s[1:-1].split(",")
return [a.strip(), b.strip()]

# Expected format is something like:
# [tuple(string, integer), tuple(string, dict(string: string)]
L = parse_list(s)
T0 = parse_tuple(L[0])
T1 = parse_tuple(L[1])
T0 = (T0[0], int(T0[1]))
T1 = (T1[0], parse_dict(T1[1]))
return [T0, T1]
That's a bit more work than eval, but I believe it is worth it.

--
Steven

Jul 7 '06 #8
Ant
[('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
[('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
# line injected by a malicious user
"__import__('os ').system('echo if I were bad I could do worse')"
[('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]
I'm curious, if you disabled import, could you make eval safe?

For example:
>>eval("__impor t__('os').syste m('echo if I were bad I could do worse')")
if I were bad I could do worse
0
>>eval("__impor t__('os').syste m('echo if I were bad I could do worse')", {'__import__': lambda x:None})
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
AttributeError: 'NoneType' object has no attribute 'system'

So, it seems to be possible to disable access to imports, but is this
enough? Are there other ways to access modules, or do damage via
built-in commands?

It seems that there must be a way to use eval safely, as there are
plenty of apps that embed python as a scripting language - and what's
the point of an eval function if impossible to use safely, and you have
to write your own Python parser!!

Jul 7 '06 #9
Ant wrote:
It seems that there must be a way to use eval safely, as there are
plenty of apps that embed python as a scripting language - and what's
the point of an eval function if impossible to use safely, and you have
to write your own Python parser!!
embedding python != accepting scripts from anywhere.

</F>

Jul 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2319
by: Richard | last post by:
I need help. I have a smarty based program that I am modifying. I have a smarty template file that consists of smarty and HTML. I need to integrate some PHP database calls into it. My problem is I cannot figure out how to pass value between smarty and PHP. Going from php to smarty I've tried this: {php} $smarty = new Smarty; $smarty->assign("x", 100);
2
1230
by: William Gower | last post by:
<Columns> <asp:TemplateColumn runat="server" HeaderText="Full Name" > <ItemTemplate> <asp:label runat="server" text='<%# DataBinder.Eval(Container.DataItem, "FirstName") + " " + DataBinder.Eval(Container.DataItem, "LastName") %>' /> </ItemTemplate> </ asp:TemplateColumn>
5
4555
by: spoilsport | last post by:
Ive got to write a multi-function program and I'm plugging in the functions but I keep getting this error from line 40. Im new to this and cant find an answer anywhere. Sam #include <stdio.h> int main (void)
4
1083
by: Steph. | last post by:
Hi, Better and better.. Now I get this error when I want to add a form to my WINDOWS FORM project : "The file could not be loaded into the Web Forms designer. Please correct the following error and then try loading it again: The designer could not be shown for this file because none of the classes within it can be designed."
3
1478
by: Larry Tate | last post by:
I have had a monstrous time getting any good debugging info out of the .net platform. Using ... ..NET Framework 1.1 Windows 2K Server VB.NET <- is this the problem? error handling in the global.asax file. I am seeing articles that say line numbers are in the ..
7
1761
by: Miguel Dias Moura | last post by:
Hello, In an ASP.Net / VB web page I want to display an image which filename depends of a parameter on the URL. I have this:
4
1630
by: Tyrone Slothrop | last post by:
File under, no favor goes unpunished. I am doing a simple (!) layout for a friend which is causing me problems. For some reason, the navigation has a four pixel upward shift in Firefox but (for once) displays properly in IE. What am I doing wrong? http://www.ispbuddy.com/Dobson/index.html
2
1111
by: shapper | last post by:
Hello, For the past month I have been spending most of my time going around ASP.NET rendering problems! For example, since when a disabled check box should be rendered the following way: <span disabled="disabled"> <input id="CheckBox1" name="CheckBox1" disabled="disabled"
2
3636
by: kheitmann | last post by:
OK, so I have a blog. I downloaded the "theme" from somewhere and have edited a few areas to suit my needs. There are different font themes within the page theme. Long story short, my "Text Posts" are supposed to be in the font: Georgia, but they are showing up in "Times New Roman"...blah! I can't find anything wrong in the code, but who am I trying to fool? I know nothing about this stuff. The code is below. The parts that I *think*...
0
9846
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9686
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10890
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10279
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7007
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5675
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4053
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3127
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.