简体   繁体   English

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

[英]How to execute a command using and log its output using logging.info in python

I want to execute a command and then log its output to a log file using logging.info 我想执行一个命令,然后使用logging.info将其输出记录到日志文件中

I am currently using 我目前正在使用

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)

but it gives me an error as $ is an invalid syntax. 但是它给我一个错误,因为$是无效的语法。

I want the output in the log file to print the value of the variable (var) 我希望日志文件中的输出打印变量(var)的值

The below method of execution works with logging.info 以下执行方法可与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 is invalid in your code. $ var在您的代码中无效。 It is invalid because the process space in which is was created is gone. 这是无效的,因为在其中创建的进程空间已消失。

Try this: 尝试这个:

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM