1

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)]
1
  • 1
    please post full invocation (what you type in bash) Commented May 6, 2014 at 12:38

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Problem is: In my code, I called every tuple in the list in a for loop (for t in argv[1] etc). However, when I do a for t in argv[1], the script doesn't understand I have a list and t is [ then ( etc. Is there a way to make it understand I have tuples?
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?
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.