【问题标题】:Reading output into variables inside the os.system command将输出读入 os.system 命令中的变量
【发布时间】: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 &lt; &lt;(sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}')") 的输出保存到变量c1, c2,...c6 中。我该怎么做。
  • /bin/sh 没有实现进程替换语法&lt;()。说真的,你为什么要在 python 中这样做?
  • 要求是在python中完成
  • 但是是否需要尝试在 /bin/sh 中使用薄 python 包装器来完成它?

标签: python linux awk os.system


【解决方案1】:

当我说“你不能在 python 中完成的任务是什么”时,这就是我的意思:

#!/usr/bin/python3
from subprocess import run, PIPE
from datetime   import datetime

output = run(['sar','-u','1','1'], stdout=PIPE).stdout.decode()
line = output.split("\n")[3]    # 4th line
values = line.split()[-6:]      # last 6 fields

now = datetime.now().strftime("%m-%d-%y-%T")

print(",".join([now] + values))

【讨论】:

  • 请注意,我并不是真正的 python 人,所以这可能不是最好的风格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
相关资源
最近更新 更多