简体   繁体   中英

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

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)

The below method of execution works with 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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