0

Using the CLI: how to I pass a parameter to TOC.action function of [1, 'happy'] or [2, 'sad'] I tried:

python TOC.action.py [1, "happy"]

python TOC.py [1, "happy"]

TOC.py

#!/usr/bin/python
import sys
   
def one(var):
    print var

def two(var):
    print var

def main(do):
    print "now what"
    print do[0]
    if do[0]==1: one(do[1])
    if do[0]==2: two(do[1]) 
    
if __name__ == '__main__':
    main(argv)
    print 'Argument List:', str(sys.argv)

2 Answers 2

2

You need to quote the arguments in the shell:

$ python TOC.py '[1, "happy"]' "[2, 'sad']"

If you want to turn the arguments into python data structures, use ast.literal_eval:

for arg in sys.argv[1:]:
    print ast.literal_eval(arg)

Once this gets too complicated, use the argparse module to handle reading the arguments.

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

1 Comment

Used $ python TOC.py '[1, "happy"]', StackTrace: action(argv) NameError: name 'argv' is not defined
0

If you're going to do anything reasonably complex with command-line arguments, then argparse really is worth using. This is especially true if you're going to use this tool with any frequency.

That said, there are also tools that are designed to make giving CLI access to python methods easier, including fabric, shovel (full disclosure, the company I work for wrote it) and others.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.