Importing a module is different from executing it as a script. If you don't trust the child Python script; you shouldn't run any code from it.
A regular way to use some code from another Python module:
import another_module
result = another_module.some_function(args)
If you want to execute it instead of importing:
namespace = {'args': [1,2,3]} # define __name__, __file__ if necessary
execfile('some_script.py', namespace)
result = namespace['result']
execfile()
is used very rarely in Python. It might be useful in a debugger, a profiler, or to run setup.py
in tools such as pip
, easy_install
.
See also runpy
module.
If another script is executed in a different process; you could use many IPC methods. The simplest way is just pipe serialized (Python objects converted to a bytestring) input args into subprocess' stdin and read the result back from its stdout as suggested by @kirelagin:
import json
import sys
from subprocess import Popen, PIPE
marshal, unmarshal = json.dumps, json.loads
p = Popen([sys.executable, 'some_script.py'], stdin=PIPE, stdout=PIPE)
result = unmarshal(p.communicate(marshal(args))[0])
where some_script.py
could be:
#!/usr/bin/env python
import json
import sys
args = json.load(sys.stdin) # read input data from stdin
result = [x*x for x in args] # compute result
json.dump(result, sys.stdout) # write result to stdout