【发布时间】:2018-07-16 10:59:26
【问题描述】:
我有一个在Linux 中运行的python 脚本。我需要捕获命令的输出并存储到变量中,然后打印输出。代码如下。
#!/usr/bin/python
import os, time
systime=os.popen('date +"%m-%d-%y-%T"').read()
os.system("read c1 c2 c3 c4 c5 c6 < <(sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}')")
os.system("echo $systime,$c1,$c2,$c3,$c4,$c5,$c6 >> outputfile.txt")
我正在使用 read 命令将命令 sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}') 给出的输出收集到 6 个变量 - c1, c2, c3, c4, c5 c6 中。当我尝试执行上述代码时,出现以下错误 -
sh: -c: line 0: syntax error near unexpected token `<'
我什至尝试使用os.popen 而不是os.system,但最终还是遇到了同样的错误。建议我如何使用os.system 命令存储变量如何在后期使用它们。我的目标是将包括时间在内的所有变量打印到输出文件outputfile.txt 中。 TIA
【问题讨论】:
-
os.system 默认使用
/bin/sh,而不是bash。此外,每个 os.system 调用都会生成一个全新的 shell,因此您要在第一个中定义的变量将在第二个中不可用。这个任务有什么是你在 python 中无法完成的? -
在使用
os.system时,我无法将命令os.system("read c1 c2 c3 c4 c5 c6 < <(sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}')")的输出保存到变量c1, c2,...c6中。我该怎么做。 -
/bin/sh 没有实现进程替换语法
<()。说真的,你为什么要在 python 中这样做? -
要求是在python中完成
-
但是是否需要尝试在 /bin/sh 中使用薄 python 包装器来完成它?
标签: python linux awk os.system