[英]Directly connect system call output to logger in Python
我正在编写一些代码,其中涉及从Python运行一些shell命令,理想情况下,我想将这些命令的输出集成到我正在使用的记录器中。 我知道我可以将stdout转移到文件/套接字中,如下所示:
call( '<a-shell-cmd>', shell=True, stdout=myFile )
但是我宁愿没有打开临时文件,循环遍历文件以写入输出,关闭文件,删除文件等操作的约束。如果仍然可以将输出直接发送到记录器,则似乎是对我来说很整洁。 有任何想法吗?
使用子流程模块 。
提示:您可以通过http://docs.python.org/release/<major>.<minor>/
特定版本python的文档。
output = subprocess.check_output(["command", "arg1"], shell=True)
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
output = os.popen('ls')
使用os.popen
output = os.popen('ls')
然后,您可以记录输出或直接在上面调用时进行输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.