當我使用Python調用外部程序.exe
時,如何從.exe
應用程序獲得printf
輸出並將其打印到我的Python IDE?如何在python腳本中獲取exe的輸出?
4
A
回答
17
要從Python調用外部程序,請使用subprocess模塊。
子流程模塊允許您產生新的進程,連接到它們的輸入/輸出/錯誤管道,並獲得它們的返回代碼。
從DOC的一個例子(output
是一個文件對象,它提供從子過程的輸出。):
output = subprocess.Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
一個具體的例子,使用cmd
,Windows命令行解釋器以2個參數:
>>> p1 = subprocess.Popen(["cmd", "/C", "date"],stdout=subprocess.PIPE)
>>> p1.communicate()[0]
'The current date is: Tue 04/14/2009 \r\nEnter the new date: (mm-dd-yy) '
>>>
6
我敢肯定,你在這裏談論的Windows(根據你的問題的措辭),但在Unix/Linux操作系統(包括Mac)的環境下,命令MODUL e是也是可用的:
import commands
(stat, output) = commands.getstatusoutput("somecommand")
if(stat == 0):
print "Command succeeded, here is the output: %s" % output
else:
print "Command failed, here is the output: %s" % output
的命令模塊提供了一個非常簡單的接口來運行命令和獲取狀態(返回代碼)和輸出(從stdout和stderr閱讀)。或者,您可以分別通過調用commands.getstatus()或commands.getoutput()來獲得狀態或僅輸出。
相關問題
- 1. 獲取python腳本的輸出從Python腳本中
- 2. 從python腳本獲取輸出到django
- 3. 如何從R腳本獲取輸出
- 4. 獲取輸出的elevaed exe
- 5. 如何在shell腳本中獲取sqlite命令的輸出
- 6. 從在Python Python腳本獲取輸出測試
- 7. 如何從PHP中的本地腳本獲取輸出?
- 8. 如何在TWebbrowser中獲取JS腳本控制檯輸出?
- 9. 從QT中的Python腳本獲取輸出
- 10. 如何從Azure ML中的python腳本獲取web服務的輸出ML
- 11. 從bash腳本獲取perl腳本的輸出並退出
- 12. 如何從gdb中獲取輸入(使用python腳本)
- 13. Selenium with Python,如何在運行腳本之後獲取頁面輸出?
- 14. 從正在運行的python腳本讀取輸出的Linux python
- 15. Python中獲取cron腳本
- 16. 獲取KeyError:在我的Python腳本中
- 17. 獲取文件輸入到Python腳本的praw腳本
- 18. Python:如何在setup.py中包含腳本的exe文件
- 19. 如何獲取動態php腳本輸出的實例?
- 20. 在shell腳本中捕獲db2輸出
- 21. Python腳本,沒有輸出?
- 22. 從服務器端python腳本獲取輸出
- 23. 從Python腳本子進程獲取輸出
- 24. 在Cocoa中獲取shell腳本的輸出
- 25. 在Xulrunner中獲取腳本輸出(shell腳本)的最佳方式是什麼?
- 26. 創建python腳本爲exe
- 27. 如何遠程運行python腳本並輸出輸出
- 28. 在PowerShell中捕獲EXE輸出
- 29. 如何在php web腳本中獲取java應用程序的輸出?
- 30. 如何在Makefile中獲取python腳本的返回值?
我可以使用os.popen()嗎? – Kim 2009-04-14 15:25:55
不,不要使用os.popen(),它已被子進程廢棄。 – unwind 2009-04-14 15:27:37