简体   繁体   中英

Directly connect system call output to logger in Python

I'm writing some code which involves running a few shell commands from Python and ideally, I would like to integrate the output from these commands into the logger that I'm using. I know I can divert stdout into a file / socket as follows:

call( '<a-shell-cmd>', shell=True, stdout=myFile )

but I'd rather not have the bind of opening a temporary file, looping over the file writing the output, closing the file, deleting the file etc. If there's anyway that I can send the output directly to the logger, it would seem a lot neater to me. Any ideas?

Use the subprocess module .

Tip: you can go to the documentation for a particular version of python via http://docs.python.org/release/<major>.<minor>/

From Python 2.7 and above:

output = subprocess.check_output(["command", "arg1"], shell=True)

In Python 2.4:

process = subprocess.Popen(["command", "arg1"], shell=True, stdout=subprocess.PIPE)
stdout,stderr = process.communicate()
# not shown: how to use Popen.poll() to wait for process death.
# while filling an output buffer
print stdout

Below Python 2.4:

output = os.popen('ls')

Use os.popen

output = os.popen('ls')

You can then log output or do it directly when calling the above.

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