Python 3 中,os.popen 函数已经被弃用,建议使用 subprocess 模块来执行命令和获取输出。
要获取 stderr 的输出,可以使用 subprocess 模块的 Popen 对象,指定 stderr 参数为 subprocess.PIPE,然后使用 communicate 方法来获取输出。
以下是一个示例:
import subprocess
cmd = "your_command_here"
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print("stdout:", stdout.decode())
print("stderr:", stderr.decode())
在上面的代码中,我们使用 Popen 对象执行命令,并指定 stdout 和 stderr 参数为 subprocess.PIPE,这将允许我们获取 stdout 和 stderr 的输出。
然后,我们使用 communicate 方法来获取输出,这将返回一个元组,其中包含 stdout 和 stderr 的输出。
最后,我们使用 decode 方法将输出从 bytes 转换为字符串,并打印出来。
如果你想要实时地获取 stderr 的输出,可以使用 stdout= subprocess.PIPE, stderr=subprocess.STDOUT,这样 stderr 的输出将被合并到 stdout 中,然后你可以使用 for line in iter(process.stdout.readline, b''): 来实时地获取输出。
例如:
import subprocess
cmd = "your_command_here"
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, b''):
print(line.decode().strip())
这将实时地打印出 stderr 的输出。