2016-11-29 107 views
-3

當我將這段代碼作爲應用程序(.exe)文件運行時,它返回一個空白輸出窗口。os.popen不能以.exe的方式工作

import os 

r = os.popen('cmd').read() 
print(r) 

(Output Window)

有人能解決我的代碼或暗示的altenative? 編輯: 我的目標是將程序作爲可執行文件運行,在DOS控制檯中運行命令並返回命令的輸出。

感謝

回答

0

os.popen

Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.

如果你只是想調用的應用程序:

os.popen('app_you_want_call.exe') 

如果你試圖用Windows命令行交互方式打球,你必須做例如:

import subprocess 
proc = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE) 
proc.stdin.write("YOUR COMMAND HERE") 

More about subprocess

+0

代碼輸出此異常: 「回溯(最近通話最後一個): 文件 「C:\ Users \用戶名爲myusername \桌面\ testing.py」,3號線,在 stdin.write(」 cmd「) NameError:name'stdin'沒有被定義 –

+0

糟糕,固定(我忘記'stdin.write'前的'proc.') – Arount

+0

謝謝你的回答,以及你對我的混亂的耐心。對不起'回合 –

相關問題