问题描述:

I tried to write a code that can execute python codes easily.

but when I used subprocess library such:

import subprocess

print(subprocess.Popen("py setup.py install", shell = True, stdout = subprocess.PIPE).stdout.read())

print(subprocess.Popen("py setup.py py2exe", shell = True, stdout = subprocess.PIPE).stdout.read())

I saw just this result

b''

please help me please

网友答案:

Most likely the commands you are trying to run are producing a stderr, which your code does not display. It is possible to send the stderr messages to stdout if you don't want to handle it separately.

I'll use a different command in the subprocess that is relatively safe. And I will break it up a little instead of having one long line.

import subprocess

p = subprocess.Popen("python filedoesntexist",
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
print(p.stdout.read())

See that I added the parameter stderr=subprocess.STDOUT, this sends all the error messages to stdout. The subprocess tries to run "python filedoesntexist" and since filedoesntexist is a file that doesn't exists, it will print this message:

b"python: can't open file 'filedoesntexist': [Errno 2] No such file or directory\n"

But you might just want to get the string instead of bytes, and you can add the parameter universal_newlines=True like this:

p = subprocess.Popen("python filedoesntexist",
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT,
                     universal_newlines=True)
print(p.stdout.read())

Now it prints just the string like this:

python: can't open file 'filedoesntexist': [Errno 2] No such file or directory

For additional information, visit the python documentation


Edit

The documentation recommends using run(), which can be done like this (updated after comments from J.F. Sebastian) :

subprocess.run(["python", "filedoesntexist"])

If you need to handle stdout in some way, add parameters described earlier in the Popen examples.

相关阅读:
Top