Validate expression/infix in python - python

How do I validate an expression/infix in python? Is it possible?
For example:
a-d*9
5-(a*0.3-d+(0.4-e))/k*5
(a-d*9)/(k-y-4.3*e)+(t-7*c)

If you want Python-style expressions, you can use the parser in the ast module and check for SyntaxError:
>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*5')
<_ast.Module object at 0x7fc7bdd9e790>
>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/ast.py", line 37, in parse
return compile(expr, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
5-(a*0.3-d+(0.4-e))/k*
^
SyntaxError: unexpected EOF while parsing
Though that might parse much more than you actually need:
>>> ast.parse('def spam(): return "ham"')
<_ast.Module object at 0x7fc7bdd9e790>
so you might want to inspect the returned parse tree carefully.

Related

How do I add image url with graph add in rdflib

I am using rdflib==4.1.2.
This is my code
>>> g=rdflib.Graph()
>>> s=rdflib.BNode()
>>> FOAF = rdflib.Namespace("http://xmlns.com/foaf/0.1/")
>>> g.bind('foaf', FOAF)
>>> g.add((s, FOAF['img'],"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcToZGEWvIBFgCiona6d74FtVthl4lkdJg3d61SGy-UCf4qFuDLD"))
I am getting this traceback.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/rdflib/graph.py", line 394, in add
"Object %s must be an rdflib term" % (o,)
AssertionError: Object https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcToZGEWvIBFgCiona6d74FtVthl4lkdJg3d61SGy-UCf4qFuDLD must be an rdflib term
How do I fix this?
Thanks!
The function Graph.add expects a tuple with three nodes as can be seen in the graph.py code:
assert isinstance(o, Node)
you can use URIRef to convert your last parameter into one (see also the examples of the documentation):
g.add((s, FOAF['img'],rdflib.URIRef("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcToZGEWvIBFgCiona6d74FtVthl4lkdJg3d61SGy-UCf4qFuDLD")))

how to use python help to file functions

If I want to see the str.replace() function: help(str.replace)
the result is:
Help on method_descriptor:
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
(END)
but how use help file.read or readlines?
for example, help(file.read) and help(read) are both errors:
>>> help(file)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
>>> help(file.read)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
>>> help(read)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'read' is not defined
How can I use help see file functions?
The file type has been removed from Python 3. Look at the io module instead:
>>> import io
>>> help(io.TextIOBase.read)
Help on method_descriptor:
read(...)
Read at most n characters from stream.
Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.

Using Python to write dbf table with fpt memos

I have a legacy application that uses .dbf and .fpt files. I am looking to read and write those files, I have figured out a way to write these files but not using fpt memos. I am using python 2.7.2 and dbf module 0.95.02. When I try to use the dbf module I get an error when trying to use FpTable.
>>> import dbf
>>> table = dbf.FpTable('test','name C(25); age N(3,0); qualified M')
>>> table
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4428, in __repr__
return __name__ + ".Table(%r, status=%r)" % (self._meta.filename, self._meta.status)
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4213, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Db3Table' object has no attribute '_meta'
>>> table.open()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4953, in open
meta = self._meta
File "/Users/doctor/.virtualenvs/dbf/lib/python2.7/site-packages/dbf.py", line 4213, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Db3Table
I am looking to create a to read and write dbf files with fpt memos. The ability to create index files .cdx would be a ideal. I am open to any way to do any of the above.
Short answer is don't use FpTable directly. You should be able to, but I've never actually tried since I always use Table(name, fields, dbf_type='fp').
Thanks for the round-a-bout bug report. ;)

dateutil.parser.parse() gives error "initial_value must be unicode or None, not str" on Windows platform

I'm sure there's a really simple solution to this, but I'm still fairly new to Python.
I'm trying to use dateutil.parser.parse() to parse a string with a timestamp in it:
>>> import dateutil.parser
>>> a = dateutil.parser.parse("2011-10-01 12:00:00+01:00")
>>> print a
2011-10-01 12:00:00+01:00
This works fine on my Linux server, but on my Windows test box it gives an error:
>>> import dateutil.parser
>>> a = dateutil.parser.parse("2011-10-01 12:00:00+01:00")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 698, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 302, in parse
res = self._parse(timestr, **kwargs)
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 350, in _parse
l = _timelex.split(timestr)
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 144, in split
return list(cls(s))
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 44, in __init__
instream = StringIO(instream)
TypeError: initial_value must be unicode or None, not str
If I try giving dateutil.parser.parse() a unicode string, that doesn't work on the Windows box either:
>>> a = dateutil.parser.parse(unicode("2011-10-01 12:00:00+01:00"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 698, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 302, in parse
res = self._parse(timestr, **kwargs)
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 350, in _parse
l = _timelex.split(timestr)
File "C:\Python27\lib\site-packages\python_dateutil-2.0-py2.7.egg\dateutil\parser.py", line 144, in split
return list(cls(s))
TypeError: iter() returned non-iterator of type '_timelex'
Yet this also works on the Linux box.
It's not a Windows issue, it's Python version / library version issue.
dateutil 2.0 is written to support only Python 3, not Python 2.X. Both cases here contain bugs when used with Python 2.X.
In the first case:
dateutil.parser.parse("2011-10-01 12:00:00+01:00")
the io.StringIO class allows only unicode arguments, but the code reads:
if isinstance(instream, str):
instream = StringIO(instream)
In the second case:
dateutil.parser.parse(unicode("2011-10-01 12:00:00+01:00"))
if you look at _timelex class, it contains the __next__ method, which is Python3's way of indicating that an object supports iteration protocol. In Python 2.X, the name of the method should be next.
Check if you have the same versions of both Python and the library on Linux and Windows. From project website:
python-dateutil-2.0.tar.gz (Python >= 3.0)
python-dateutil-1.5.tar.gz (Python < 3.0)

How can I convert string to "command" in Python?

How can I convert this so it could execute?
Traceback (most recent call last):
File "C:\Users\Shady\Desktop\tet.py", line 14, in <module>
exec test
File "<string>", line 1
print "hello world"
^
IndentationError: unexpected indent
source:
test = ''.join(clientIp.split("test6")[1:])
You might need to use lstrip() on the string to get rid of any leading whitespace before passing it to exec.

Categories