简体   繁体   中英

Execution of a python script from ubuntu shell

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)]

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 eg in the syntax of the case statement. Square brackets are used for wildcards.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM