os.popen() 自 Python 2.6 起已被弃用。您现在应该使用 subprocess 模块:http://docs.python.org/2/library/subprocess.html#subprocess.Popen
import subprocess
command = "gcc -E myHeader.h" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
#Launch the shell command:
output = process.communicate()
print output[0]
在 Popen 构造函数中,如果 shell 为 True,则应将命令作为字符串而不是序列传递。否则,只需将命令拆分为一个列表:
command = ["gcc", "-E", "myHeader.h"] # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
如果您还需要读取标准错误,进入 Popen 初始化,您可以将 stderr 设置为 subprocess.PIPE 或 subprocess.STDOUT em>:
import subprocess
command = "gcc -E myHeader.h" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
#Launch the shell command:
output, error = process.communicate()