In the following code sample, the last line (print buildConnectionString(myParams)) is throwing the following error:
Invalid syntax
def buildConnectionString(params):
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret"
}
print buildConnectionString(myParams)
Assuming that you're on Python 3, print is a function and needs to be wrapped in parentheses:
print(buildConnectionString(myParams))
Related
I cannot understand what the syntax error is.
application(environ,start_response):
status = '200 OK'
html = '<html>\n' \
'<body>\n' \
' Hooray, mod_wsgi is working\n' \
'</body>\n' \
'</html>\n'
response_header = [('Content-type','text/html')]
start_response(status,response_header)
return [html]
File "test_wsgi_script.py", line 1 application(environ,start_response):
^
SyntaxError: invalid syntax
(scripts) root#django:/var/www/scripts#
Do need def in front of the function call?
def application(environ,start_response):
I'm trying to edit Norvig's lispy.py scheme-to-python interpreter for a racket program in which, in addition to the procedures he includes, I use string->jsexpr and string-replace.
To do this, I edited his add_globals function as follows.
def add_globals(self):
"Add some Scheme standard procedures."
import math, cmath, operator as op
self.update(vars(math))
self.update(vars(cmath))
self.update({
'+':op.add, '-':op.sub, '*':op.mul, '/':op.div, 'not':op.not_,
'>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq,
'equal?':op.eq, 'eq?':op.is_, 'length':len, 'cons':cons,
'car':lambda x:x[0], 'cdr':lambda x:x[1:], 'append':op.add,
'list':lambda *x:list(x), 'list?': lambda x:isa(x,list),
'null?':lambda x:x==[], 'symbol?':lambda x: isa(x, Symbol),
'boolean?':lambda x: isa(x, bool), 'pair?':is_pair,
'port?': lambda x:isa(x,file), 'apply':lambda proc,l: proc(*l),
'eval':lambda x: eval(expand(x)), 'load':lambda fn: load(fn), 'call/cc':callcc,
'open-input-file':open,'close-input-port':lambda p: p.file.close(),
'open-output-file':lambda f:open(f,'w'), 'close-output-port':lambda p: p.close(),
'eof-object?':lambda x:x is eof_object, 'read-char':readchar,
# Additions below
'reverse':lambda x: x[::-1],
'string->jsexpr':lambda x: json.loads(x),
'string-replace':lambda strng,x,y: strng.replace(x, y),
# Additions above
'read':read, 'write':lambda x,port=sys.stdout:port.write(to_string(x)),
'display':lambda x,port=sys.stdout:port.write(x if isa(x,str) else to_string(x))})
return self
In the lispy repl, string-replace seems to succeed:
% python lispy.py
Lispy version 2.0
lispy> (string-replace "[['Noth', '<b>ing</b>'], ' in']" "\'" "\"")
"[[\"Noth\", \"<b>ing</b>\"], \" in\"]"
lispy>
However when, at the end of lispy.py, I run
if __name__ == '__main__':
x = eval(parse("""(begin
(string-replace "[['Noth', '<b>ing</b>'], ' in']" "\'" "\"")
)
"""
))
print x
instead of running this (which is how the file came),
if __name__ == '__main__':
repl()
the program hangs — and when I trace it, I see that there's an infinite loop.
Any ideas?
Got it. I needed to add an extra backslash to escape the escape in the triple quoted section, like this
if __name__ == '__main__':
x = eval(parse("""(begin
(string-replace "[['Noth', '<b>ing</b>'], ' in']" "\\'" "\\"")
)
"""
))
print x
I have written following script in perl and trying to pass python.
Input : D1 and D2 are array and plotanalysis is python script
my #D1=([],[]);
my #D2=([],[]);
my $cmd="plotanalysis -d1 #D1 -d2 #D2";
print STDERR "***Info : plotanalysis command $cmd\n";
if(system($cmd)!=0)
{
print STDERR "plotanalysis did not run";
}
Expecting : I was expecting array will pass to python script But getting following info
Getting following line
plotanalysis command plotanalysis -d1 ARRAY(0x873b58) ARRAY(0x873b88) -d2 ARRAY(0xa3ffa0) ARRAY(0xa3ffd0)
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `plotanalysis -d1 ARRAY(0x873b58) ARRAY(0x873b88) -d2 ARRAY(0xa3ffa0) ARRAY(0xa3ffd0)'
Any input/suggestion to fix issue. I also need to capture return value from python script. may i know how can be handle?
In python script, I have make as string
def parse_args(args):
"""Parse the argument"""
parser = argparse.ArgumentParser(description='check function',
epilog="""
for reporting any issue""")
parser.add_argument('-d1', '-data1', dest='data_1', required=True,
nargs = "*",
help = "x and y data for calculation")
parser.add_argument('-d2', '-data2', dest='data_2', required=True,
nargs = "*",
help = "x and y data for calculation")
args = parser.parse_args(args)
return args
def main(args):
"""Invoke main functionality"""
print (args)
if __name__ == "__main__":
sys.exit(main(parse_args(sys.argv[1:])))
I have done following update which help me get desired value
my $cmd="plotanalysis -d1 '#{$D1[1]}' -d2 '#{$D2[1]}'";
print STDERR "***Info : plotanalysis command $cmd\n";
if(system($cmd)!=0)
{
print STDERR "plotanalysis did not run";
}
I have just started with python. I was executing a simple program given in 'Dive into Python' by Mark Pilgrim in Ubuntu. The program is as follows:
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
}
print buildConnectionString(myParams)
But it is showing error as follows:
File "./1.py", line 3
Returns string."""
^
IndentationError: expected an indented block
I have tried few things like giving a space in front of return on line 3, then instead of space using a tab.
Can anybody help me in finding out what the error is about, why it has came, etc. and also with some easy tutorials with which a can go ahead.
Thanks in advance..
Try it like this:
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
}
print buildConnectionString(myParams)
BTW: Do you understand the structure? Function, if __name__=="__main__": block etc.?
Why not read the Python documentation? It might help. ;)
http://docs.python.org/2/reference/lexical_analysis.html#indentation
When ever I encounter a 2-character attribute in my XML stream when parsing with xml.sax under Jython 2.5.2 it converts the attribute name to a tuple. No amount of coercion of that name allows me to extract the value for the attribute. I tried passing the tuple or converting it to a string and passing that. Both cases result in:
Traceback (most recent call last):
File "test.py", line 18, in startElement
print '%s = %s' % (k, attrs.getValue(k))
File "/usr/local/Cellar/jython/2.5.2/libexec/Lib/xml/sax/drivers2/drv_javasax.py", line 266, in getValue
value = self._attrs.getValue(_makeJavaNsTuple(name))
TypeError: getValue(): 1st arg can't be coerced to String, int
I've got some sample code you can run that shows the problem:
import xml
from xml import sax
from xml.sax import handler
import traceback
class MyXMLHandler( handler.ContentHandler):
def __init__(self):
pass
def startElement(self, name, attrs):
for k in attrs.keys():
print 'type(k) = %s' % type(k)
if isinstance(k, (list, tuple)):
k = ''.join(k)
print 'type(k) = %s' % type(k)
print 'k = %s' % k
try:
print '%s = %s' % (k, attrs.getValue(k))
except Exception, e:
print '\nError:'
traceback.print_exc()
print ''
if __name__ == '__main__':
s = '<TAG A="0" AB="0" ABC="0"/>'
print '%s' % s
xml.sax.parseString(s, MyXMLHandler())
exit(0)
When run, the AB attribute is returned as a tuple but the A and ABC attributes are unicode strings and function properly with the get() method on the Attribute object. Under Jython 2.5.2 this outputs, for me:
> jython test.py
<TAG A="0" AB="0" ABC="0"/>
type(k) = <type 'unicode'>
type(k) = <type 'unicode'>
k = A
A = 0
type(k) = <type 'tuple'>
type(k) = <type 'unicode'>
k = AB
Error:
Traceback (most recent call last):
File "test.py", line 18, in startElement
print '%s = %s' % (k, attrs.getValue(k))
File "/usr/local/Cellar/jython/2.5.2/libexec/Lib/xml/sax/drivers2/drv_javasax.py", line 266, in getValue
value = self._attrs.getValue(_makeJavaNsTuple(name))
TypeError: getValue(): 1st arg can't be coerced to String, int
type(k) = <type 'unicode'>
type(k) = <type 'unicode'>
k = ABC
ABC = 0
This code functions correctly under Python 2.7.2 on OS X and Python 2.4.3 on CentOS 5.6. I dug around Jython bugs but couldn't find anything similar to this issue.
Is it a known Jython xml.sax handling problem? Or have I messed up something in my Handler that's 2.5.2 incompatible?
Edit: this appears to be a Jython 2.5.2 bug. I found a reference to it: http://sourceforge.net/mailarchive/message.php?msg_id=27783080 -- suggestions for a workaround welcome.
So, this is a reported bug in Jython. It took some digging but I found it in their bug archive:
http://bugs.jython.org/issue1768
The second comment on the bug provides a work-around for the issue: use the _attrs.getValue() method to retrieve values off the attributes list. Like so:
attrs._attrs.getValue('id')
My re-written code works if I change the line:
print '%s = %s' % (k, attrs.getValue(k))
to:
print '%s = %s' % (k, attrs._attrs.getValue(k))
The more flexible works-in-python-and-jython solution is to build a helper:
def _attrsGetValue(attrs, name, default=None):
value = None
if 'jython' in sys.executable.lower():
value = attrs._attrs.getValue(name)
if not name:
value = default
else:
value = attrs.get(name, default)
return value