簡體   English   中英

將輸出讀入os.system命令中的變量

[英]Reading output into variables inside the os.system command

我有一個在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")

我正在收集命令sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}')給出的輸出sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}') 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命令存儲變量, os.system如何在以后的階段中使用它們。 我的目標是將所有變量(包括被捕獲的時間)打印到輸出文件outputfile.txt TIA

這就是我說“無法在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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM