简体   繁体   English

将系统调用输出直接连接到Python中的记录器

[英]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. 我正在编写一些代码,其中涉及从Python运行一些shell命令,理想情况下,我想将这些命令的输出集成到我正在使用的记录器中。 I know I can divert stdout into a file / socket as follows: 我知道我可以将stdout转移到文件/套接字中,如下所示:

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>/ 提示:您可以通过http://docs.python.org/release/<major>.<minor>/特定版本python的文档。

From Python 2.7 and above: 从Python 2.7及更高版本开始:

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

In Python 2.4: 在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: 在Python 2.4以下:

output = os.popen('ls')

Use os.popen 使用os.popen

output = os.popen('ls')

You can then log output or do it directly when calling the above. 然后,您可以记录输出或直接在上面调用时进行输出。

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

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