[英]How to execute a command using and log its output using logging.info in python
我想執行一個命令,然后使用logging.info將其輸出記錄到日志文件中
我目前正在使用
cmd = """var=$(cat ip.txt | head -1 | sed 's/[^|]//g' | awk '{ print length }')"""
logging.info(cmd)
process = os.popen(cmd)
processClose = process.close()
logging.info($var)
但是它給我一個錯誤,因為$是無效的語法。
我希望日志文件中的輸出打印變量(var)的值
以下執行方法可與logging.info一起使用
success = sp.call(cmd, stdout=open('temp_log', 'w'), stderr=open('temp_err_log', 'w'), shell = True)
outText = open('temp_log').readlines()
outText = ''.join(outText)
logging.info('Dump stderr:\n%s'%(outText))
$ var在您的代碼中無效。 這是無效的,因為在其中創建的進程空間已消失。
嘗試這個:
import subprocess
cmd = "cat ip.txt | head -1 | sed 's/[^|]//g' | awk '{ print length }'"
p = subprocess.Popen([cmd,], stdout=subprocess.PIPE, shell=True)
p.stdout.readline()
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.