2016-02-29 93 views
0

我想從Python中執行以下Windows 7的命令:使用Python來設置Windows路徑和調用多個命令

SET PATH=%PATH%;C:\Qt\Qt5.5.1\5.5\mingw492_32\bin;C:\Qt\Qt5.5.1\Tools\mingw492_32\bin 

C:\Qt\Qt5.5.1\5.5\mingw492_32\bin\qmake untitled5.pro 
C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make 
C:\Qt\Qt5.5.1\Tools\mingw492_32\bin\mingw32-make clean 

我想:

os.system("SET PATH=%PATH%;C:\\Qt\\Qt5.5.1\\5.5\\mingw492_32\\bin;C:\\Qt\\Qt5.5.1\\Tools\\mingw492_32\\bin") 
os.system("qmake untitled5.pro") 
os.system("mingw32-make.exe") 
os.system("mingw32-make clean") 

不過的了:

'qmake' is not recognized as an internal or external command, 
operable program or batch file. 

'mingw32-make.exe' is not recognized as an internal or external command, 
operable program or batch file. 

'mingw32-make' is not recognized as an internal or external command, 
operable program or batch file. 

看來PATH沒有改變。有人會提出一個想法嗎?

如果我把這些命令放在cmd.bat然後調用os.system("cmd.bat")它就起作用了。但我寧願不創建這個額外的文件(cmd.bat)。

+0

創建['subprocess.Popen'](https://docs.python.org/2/library/subprocess.html?highlight=popen#subprocess.Popen)類的一個實例和通過'env'關鍵字參數傳遞你想要的環境。 – martineau

+0

爲什麼你需要使用python呢? –

+0

我打算從Jenkins調用Python腳本。到目前爲止,我正在使用Bash和/或Bat腳本。 – KcFnMi

回答

0

環境變量只存在於進程和子進程中。你正在做的是產生一個子進程,設置路徑環境變量,然後退出該進程,失去它的環境。

將所有內容放入批處理文件是解決此問題的一種方法。你也可以使用子進程生成一個命令shell,然後通過stdin管道命令。

參見:How do I write to a Python subprocess' stdin?

0

許多subprocess的命令讓你通過使用子進程的環境。你可以複製你的環境,改變你想要的,然後執行命令。您甚至可以從頭開始創建環境,以便在當前環境中發生的任何事情都會混淆您所調用的內容。下面是一個例子

import os 
import subprocess as subp 

environ = os.environ.copy() 
environ['PATH'] = os.pathsep.join(environ['PATH'], 
    ["C:\\Qt\\Qt5.5.1\\5.5\\mingw492_32\\bin", 
    "C:\\Qt\\Qt5.5.1\\Tools\\mingw492_32\\bin"]) 

subp.call(["qmake", "untitled5.pro", env=environ) 
subp.call(["mingw32-make.exe"], env=environ) 
subp.call(["mingw32-make", "clean"], env=environ)