简体   繁体   English

Python子进程使用import子进程

[英]Python subprocess using import subprocess

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. 问题是,我有一个现成的应用程序需要调用Python脚本。 This script on its own works perfectly, but it needs to call existing shell scripts. 这个脚本本身可以很好地工作,但它需要调用现有的shell脚本。

Schematically the problem is in the following code: 示意图问题在以下代码中:

parent.py parent.py

import subprocess
subprocess.call(['/usr/sfw/bin/python', '/usr/apps/openet/bmsystest/relAuto/variousSW/child.py','1', '2'])

child.py child.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

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 python and /usr/sfw/bin/python . 您正在使用python/usr/sfw/bin/python

  1. Is bare python pointing to the same python? 裸蟒是指向同一个蟒蛇?
  2. 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 code to 或者,您可以将parent.py code更改为

import subprocess
subprocess.call(['python', '/usr/apps/openet/bmsystest/relAuto/variousSW/child.py','1', '2'])

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. 是的,这是不好的方式,但它可以帮助你。

Using subprocess.call is not the proper way to do it. 使用subprocess.call不是正确的方法。 In my view, subprocess.Popen would be better. 在我看来, subprocess.Popen会更好。

parent.py: parent.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 child.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM