[英]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.