I wrote a python script I want to call from an ubuntu shell. One of the arguments of my function is a list of tuples. However, when I write this list of tuples, the following error is raised:
bash: syntax error near unexpected token '('
How can I ignore the '('?
Invocation:
python scriptName.py [(1,2,3), (4,3,5), (3,4,5)]
-
1please post full invocation (what you type in bash)m.wasowski– m.wasowski2014年05月06日 12:38:22 +00:00Commented May 6, 2014 at 12:38
2 Answers 2
The shell does not like your list of arguments, because it contains characters which have special meaning to the shell.
You can get around that with quoting or escaping;
python scriptName.py '[(1,2,3), (4,3,5), (3,4,5)]'
or if your script really wants three separate arguments and glues them together by itself
python scriptName.py '[(1,2,3),' '(4,3,5),' '(3,4,5)]'
Better yet, change your script so it can read an input format which is less challenging for the shell. For large and/or complex data sets, the script should probably read standard input (or a file) instead of command-line arguments.
(Parentheses start a subshell and are also used e.g. in the syntax of the case statement. Square brackets are used for wildcards.)
2 Comments
eval and in Python 2 input do this sort of parsing. Using Python's internal representation for your data may not be ideal, though. Perhaps it would make sense to use e.g. JSON for input?You need to quote your argument, so it will be treated as single string. Then you can access it from sys.argvs:
#!/usr/bin/env python
import sys
import ast
try:
literal = sys.argv[1]
except KeyError:
print "nothing to parse"
sys.exit(1)
try:
obj = ast.literal_eval(literal)
except SyntaxError:
print "Could not parse '{}'".format(literal)
sys.exit(2)
print repr(obj)
print type(obj)
Then in bash:
$ python literal.py "[(1,2,3), (4,3,5), (3,4,5)]"
[(1, 2, 3), (4, 3, 5), (3, 4, 5)]
<type 'list'>
For more about command line syntax in bash, see:
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Syntax