简体   繁体   中英

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:

#!/usr/bin/env python
import subprocess

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

On POSIX, it is equvalent to:

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

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

Or is there a great reason for trying to nest this inside a shell?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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