使用导入子进程的 Python 子进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4364087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python subprocess using import subprocess
提问by apllom
Can this be somehow overcome? Can a child process create a subprocess?
这可以以某种方式克服吗?子进程可以创建子进程吗?
The problem is, I have a ready application which needs to call a Python script. This script on its own works perfectly, but it needs to call existing shell scripts.
问题是,我有一个需要调用 Python 脚本的现成应用程序。这个脚本本身可以完美运行,但它需要调用现有的 shell 脚本。
Schematically the problem is in the following code:
从原理上讲,问题出在以下代码中:
parent.py
父母.py
import subprocess
subprocess.call(['/usr/sfw/bin/python', '/usr/apps/openet/bmsystest/relAuto/variousSW/child.py','1', '2'])
child.py
孩子.py
import sys
import subprocess
print sys.argv[0]
print sys.argv[1]
subprocess.call(['ls -l'], shell=True)
exit
Running child.py
运行 child.py
python child.py 1 2
all is ok
Running parent.py
运行 parent.py
python parent.py
Traceback (most recent call last):
File "/usr/apps/openet/bmsystest/relAuto/variousSW/child.py", line 2, in ?
import subprocess
ImportError: No module named subprocess
回答by pyfunc
There should be nothing stopping you from using subprocess in both child.py and parent.py
应该没有什么可以阻止您在 child.py 和 parent.py 中使用子进程
I am able to run it perfectly fine. :)
我能够完美地运行它。:)
Issue Debugging:
问题调试:
You are using
pythonand/usr/sfw/bin/python.
您正在使用
python和/usr/sfw/bin/python。
- Is bare python pointing to the same python?
- Can you check by typing 'which python'?
- 裸蟒是否指向同一个蟒蛇?
- 你能通过输入'which python'来检查吗?
I am sure if you did the following, it will work for you.
我相信如果你做了以下事情,它会对你有用。
/usr/sfw/bin/python parent.py
Alternatively, Can you change your parent.py codeto
或者,你可以改变你parent.py code的
import subprocess
subprocess.call(['python', '/usr/apps/openet/bmsystest/relAuto/variousSW/child.py','1', '2'])
回答by pod2metra
Using subprocess.callis not the proper way to do it. In my view, subprocess.Popenwould be better.
使用subprocess.call不是正确的方法。在我看来,subprocess.Popen会更好。
parent.py:
父母.py:
1 import subprocess
2
3 process = subprocess.Popen(['python', './child.py', 'arg1', 'arg2'],\
4 stdin=subprocess.PIPE, stdout=subprocess.PIPE,\
5 stderr=subprocess.PIPE)
6 process.wait()
7 print process.stdout.read()
child.py
孩子.py
1 import subprocess
2 import sys
3
4 print sys.argv[1:]
5
6 process = subprocess.Popen(['ls', '-a'], stdout = subprocess.PIPE)
7
8 process.wait()
9 print process.stdout.read()
Out of program:
节目外:
python parent.py
['arg1', 'arg2']
.
..
chid.py
child.py
.child.py.swp
parent.py
.ropeproject
回答by Jimilian
You can try to add your python directory to sys.path in chield.py
您可以尝试将您的 python 目录添加到 chield.py 中的 sys.path
import sys
sys.path.append('../')
Yes, it's bad way, but it can help you.
是的,这是不好的方式,但它可以帮助你。

