简体   繁体   English

Python子进程:如何在python中执行进程的子进程?

[英]Python subprocess: How can I execute a sub-process of a process in python?

I want to be able to run the following command: 我希望能够运行以下命令:

sh -c "python -c "import sys;sys.platform""

however I am failing to do so with subprocess 但是我没有用子进程这样做

I have tried the following but 我试过以下但是

subprocess.check_output(["sh", "-c", ["python", "-c",  '"import sys; print sys.platform"']])

I get the following output: 我得到以下输出:

sh: python-cimport: command not found
File "<string>", line 1
    "import
          ^

In the order of preference (how to print the platform info): 按优先顺序(如何打印平台信息):

#!/usr/bin/env python
import platform

print(platform.platform())

If you want to run it as a separate process: 如果要将其作为单独的进程运行:

#!/usr/bin/env python
import subprocess
import sys

subprocess.check_call([sys.executable or 'python', '-m', 'platform'])

If you want to run in a shell: 如果你想在shell中运行:

#!/usr/bin/env python
import subprocess

subprocess.check_call('python -m platform', shell=True)

On POSIX, it is equvalent to: 在POSIX上,它等价于:

subprocess.check_call(['/bin/sh', '-c', 'python -m platform'])

Your specific command: 你的具体命令:

subprocess.check_call(['/bin/sh', '-c', 
                       "python -c 'import sys; print(sys.platform)'"])

Your quotes are getting tangled up with each other. 你的报价相互纠缠在一起。 Try: 尝试:

sh -c 'python -c "import sys; print sys.platform"'

Or, if you're trying to call it from inside another python program, perhaps you mean to say this... 或者,如果你试图从另一个python程序中调用它,也许你的意思是这样说......

subprocess.check_output(['python', '-c', 'import sys; print sys.platform'])

Or is there a great reason for trying to nest this inside a shell? 或者是否有一个很好的理由尝试将其嵌入shell中?

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

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