通过 shell 子处理结果而不是保存到文本文件中
Subprocess result through shell instead of being saved into text file
我正在为我的论文研究编写一个 Python 脚本,但我遇到了 subprocess 模块的问题。
脚本所做的是使用大量参数执行 "perf"(这里是一个简化版本):
cmd = 'sudo perf stat -C %s -I %s -x , -e "%s"' % (core_perf, interval, perf_event_text)
然后我将 cmd 拆分为 args,以便将令牌发送到子进程:
final_cmd = cmd.split()
with open('output.txt', 'w') as outfile:
subprocess.Popen(final_cmd, stdout=outfile)
问题是这很好用,但是输出是通过 shell 显示的,而不是保存到文件中。
如果我为 "ls" 这样做,它就像一个魅力:
with open('output.txt', 'w') as outfile:
subprocess.Popen("ls", stdout=outfile)
有什么想法吗?
如有任何帮助,我们将不胜感激!
提前致谢!
perf stat
不使用 stdout
作为其输出,但 stderr
,许多程序启动命令并报告它(例如 time
)做同样的事情不会破坏已执行命令的输出。
所以在这种情况下,使用 stderr=outfile
.
而不是 stdout=outfile
另一种选择是将 -o
参数传递给 perf
,以便将 stderr 输出写入您指定的文件:
import shlex
import subprocess
cmd = shlex.split('perf stat -o outfile.txt ls')
subprocess.call(cmd)
我正在为我的论文研究编写一个 Python 脚本,但我遇到了 subprocess 模块的问题。
脚本所做的是使用大量参数执行 "perf"(这里是一个简化版本):
cmd = 'sudo perf stat -C %s -I %s -x , -e "%s"' % (core_perf, interval, perf_event_text)
然后我将 cmd 拆分为 args,以便将令牌发送到子进程:
final_cmd = cmd.split()
with open('output.txt', 'w') as outfile:
subprocess.Popen(final_cmd, stdout=outfile)
问题是这很好用,但是输出是通过 shell 显示的,而不是保存到文件中。
如果我为 "ls" 这样做,它就像一个魅力:
with open('output.txt', 'w') as outfile:
subprocess.Popen("ls", stdout=outfile)
有什么想法吗?
如有任何帮助,我们将不胜感激!
提前致谢!
perf stat
不使用 stdout
作为其输出,但 stderr
,许多程序启动命令并报告它(例如 time
)做同样的事情不会破坏已执行命令的输出。
所以在这种情况下,使用 stderr=outfile
.
stdout=outfile
另一种选择是将 -o
参数传递给 perf
,以便将 stderr 输出写入您指定的文件:
import shlex
import subprocess
cmd = shlex.split('perf stat -o outfile.txt ls')
subprocess.call(cmd)