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