如何使用python中的logging.info使用命令并记录其输出

时间:2016-12-27 15:16:47

标签: python unix logging

我想执行一个命令,然后使用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)的值

2 个答案:

答案 0 :(得分:1)

以下执行方法适用于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))

答案 1 :(得分:0)

$ 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()

希望这有帮助。