Am trying to extract command line arguments passed in python
cmdargs = str(sys.argv)
print cmdargs
it prints
['E:/omation.py', '{"command":"sel_media","value":"5X7_phot
o_paper.png"},{"command":"tray","value":"4X6_photo_paper.png"}']
from this how can i extract command and values .
i dont knoe how to loop this array and get the commnd and value values.plese help
Note: i also want to discard the first value 'E:/omation.py'
-
Is that exactly what it prints? Cause looks like there is a missing quote.Jayanth Koushik– Jayanth Koushik2014年04月02日 06:58:08 +00:00Commented Apr 2, 2014 at 6:58
-
That is not valid JSON. How about passing the two objects as separate arguments?user1907906– user19079062014年04月02日 07:02:01 +00:00Commented Apr 2, 2014 at 7:02
3 Answers 3
You can use Python utils to parse json strings:
import json
examples = json.loads('['+cmdargs[1]+']')
The first import loads json utilities for python. Then, you can parse a json string into a Python dictionary by using json.loads. In the example, I have parsed one of your json strings into a python dictionary. Remember to add '[' and ']' to convert your string to a valid json array. Then, you can get a command and a value like :
print(examples[0]['command'])
print(examples[0]['value' ])
2 Comments
The example you give shows two json objects in the second element of the list cmdargs. Probably the easiest way to capture that case would be to enclose that second argument in square braces, which would make it legal JSON, then loop through the resulting list:
import json
a = json.loads('['+cmdargs[1]+']')
for p in a:
print "command is ", p['command']
print "value is ", p['value']
This is specific to the example you showed, you may need to make it more robust for your purposes.
Comments
Your input is not valid JSON. You must find a way to pass the arguments as separate, valid JSON objects. Then you can do this:
# j.py
import json
import sys
print(sys.argv)
for arg in sys.argv[1:]:
j = json.loads(arg)
print(j.get("command"))
print(j.get("value"))
Usage could be:
$ python3 j.py '{"command":"sel_media","value":"5X7_photo_paper.png"}' '{"command":"tray","value":"4X6_photo_paper.png"}'
['j.py', '{"command":"sel_media","value":"5X7_photo_paper.png"}', '{"command":"tray","value":"4X6_photo_paper.png"}']
sel_media
5X7_photo_paper.png
tray
4X6_photo_paper.png
13 Comments
import simplejson as json not usinh josnprint(sys.argv) value only after that nothing gettingimport sys sys.path.append('C:\ProgramData\SikuliX\Lib\simplejson-3.3.3' ) import os import simplejson as json print(sys.argv) for arg in sys.argv[1:]: j = json.loads(arg) print(j.get("command")) print(j.get("value"))