问题
I'm on linux, and I have one python script that I want to call from another python script. I don't want to import it as a module (for a layer of security, and now for an academic exercise because I want to figure this out), I want to actually have one script call the other with os.system() or another function like that, and have the other script return a list of tuples to the first script.
I know this might not be the optimal way to do it, but I'd like to try it out, and learn some stuff in the process.
回答1:
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
回答2:
You can use subprocess:
subprocess.call(["python", "myscript.py"])
This will also return the process return value (such as 0 or 1).
回答3:
You will need some kind of serialization to return a list. I'd suggest pickle or JSON.
Your other script will print it to stdout
and the calling script will read it back and deserialize.
回答4:
You know, ZMQ is very useful for inter proces communication. You can well use it with json objects.
Here is the python binding
回答5:
It's very simple.
import popen2
fout, fin = popen2.popen2('python your_python_script.py')
data = fout.readline().strip()
if data <> '':
# you have your `data`, so do something with it
来源:https://stackoverflow.com/questions/16877323/getting-return-information-from-another-python-script