2016-06-10 37 views
1

FILE - a.pyPass Wörterbuch als Befehlszeilenargument

import os 
toolObj = { 
    'CLIENT_IP': u'10.193.xyz.xyz', 
    'CMD_KEY': 8000, 
    'CMD_WD': None, 
    'CMD': u'date', 
    'NUM_INSTANCE': '', 
    'DURATION': -1, 
    'TIME_OUT': '', 
    'PORT': '', 
    'CNFG_PARAM': '', 
    'MSG_TYPE': '', 
    'NUM_ITER': '', 
    'CMD_HASH': '1475212' 
} 
print os.popen('python b.py %s'%toolObj).read() 

FILE - b.py

import sys, ast<br> 
print sys.argv 
toolObj = ast.literal_eval(sys.argv[1]) 
print 'using ast', toolObj 

Auf a.py Ausführen ich die folgende Fehlermeldung erhalten:

Traceback (most recent call last): 
File "96_.py", line 16, in 
toolObj = ast.literal_eval(sys.argv[1]) 
File "/usr/local/lib/python2.7/ast.py", line 49, in literal_eval 
node_or_string = parse(node_or_string, mode='eval') 
File "/usr/local/lib/python2.7/ast.py", line 37, in parse 
return compile(source, filename, mode, PyCF_ONLY_AST) 
File "", line 1 
{CLIENT_IP: 
^ SyntaxError: unexpected EOF while parsing 
['96_.py', '{CLIENT_IP:', 'u10.193.xyz.xyz,', 'CMD_KEY:', '8000,', 'CMD_WD:', 'None,', 'CMD:', 'udate,', 'NUM_INSTANCE:', ',', 'DURATION:', '-1,', 'TIME_OUT:', ',', 'NUM_ITER:', ',', 'CNFG_PARAM:', ',', 'MSG_TYPE:', ',', 'PORT:', ',', 'CMD_HASH:', '1475212}'] 

Ich habe versucht json & cPickle beide nicht funktioniert.

+0

Warum importieren Sie 'b.py' nicht direkt? – SiHa

Antwort

1

Fügen Sie einfach doppelte Anführungszeichen um das Wörterbuch:

print os.popen('python b.py "%s"'%toolObj).read() 
0

Json das zuverlässigste Format ist ein Python-Wörterbuch in eine Zeichenfolge zu verwenden, für die Serialisierung.

# b.py 
import json, sys 
toolObj = json.loads(sys.argv[1]) 
print toolObj 

# a.py 
import json, os 
toolObj = dict(a=1, b='foo', c=None) 
# using %r in the format string makes sure special characters are escaped. 
cmd = 'python b.py %r' % json.dumps(toolObj) 
# cmd is now: 
# python b.py '{"a": 1, "c": null, "b": "foo"}' 

print os.popen(cmd).read() 
# output is: 
# {u'a': 1, u'c': None, u'b': u'foo'}