[英]cmd executes but python os.popen and subprocess.call and subprocess.popen and os.system does not execute, why?
[英]os.system to subprocess.Popen or subprocess.call
我有一個下面的函數,當我在CMD中執行python代碼(SIMT是可執行文件)時,它可以正常工作。 但是,當我使用py2exe構建可執行文件時,shell窗口會快速出現並消失。 因此,我搜索並發現可以使用帶有creationflags = 0x08000000的subprocess.popen。 但這行不通。
這是我的職責
def Kill(SIMT):
outfile1 = open('Kill.txt', 'w')
outfile1.write('Kill' + '\r\n')
outfile1.write('x')
outfile1.close()
os.system("type Kill.txt | testclient p . " + SIMT)
os.remove('Kill.txt')
我用以下代碼替換了os.system:
subprocess.Popen(["type Kill.txt | testclient p . ", SIMT], creationflags= 0x08000000, shell=True).communicate()
另外,我是否需要shell = True?
如果您希望shell為您安排管道,則需要具有shell=True
並將第一個參數設置為字符串,就像os.system
而不是列表一樣。 在shell=False
,列表意味着執行作為列表的第一項給出的程序,而其他項則作為列表的命令行參數; 因此您不能讓第一項包含|
並期望shell代表您安排該管道。
您的替代方法是Kill.txt
安排“管道”或其等效項-例如,在這里可能最簡單,只需在Kill.txt
打開一個文件對象作為subprocess.Popen
的標准輸入( stdin=
)。 testclient
只執行testclient
(I相信type
除了將文件讀出到stdout之外什么也沒做,因此對於這種特定的用例就足夠了)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.