2017-05-28 164 views
0

我試圖運行一種利用Python和PowerShell腳本的應用程序。我已經編寫了Python腳本和PowerShell腳本,它們可以同時工作,但彼此分離。我想要做的是創建一個啓動它們的Python程序,有沒有辦法?謝謝! 我有什麼權利,現在,作爲一個更大的腳本的一部分,是:在Python外執行PowerShell腳本

import subprocess 
autom = r"C:\Users\mrmostacho\Desktop\Robot\Autom.ps1","-ExecutionPolicy","Unrestricted" 
powershell = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" 
subprocess.Popen("%s %s" % (powershell, autom,)) 
+0

你嘗試過這麼遠嗎?提示:https://docs.python.org/3/library/subprocess.html – cdarke

+0

我試過使用運行該文件和PoweSshell.exe的subprocess.Popen,但是,它會將Python窗口重命名爲PowerShell ,但書面PowerShell程序不會啓動 – Esteb37

+0

如果這是您的問題,然後顯示您的代碼,並有人可能能夠幫助你。 – cdarke

回答

1

我想你不想"-ExecutionPolicy","Unrestricted"作爲腳本參數,而是要設置powershells執行政策,讓您的腳本的執行。因此,您應該在實際腳本之前傳遞這些參數。第二種:將腳本作爲參數傳遞給powershell.exe是不夠的(這種方式腳本名稱被解釋爲Powershell命令,並且必須根據powershells引用規則轉義該名稱)。這是不夠的。相反,腳本名稱應在-File參數後給出。從powershell /?

-File 
    Führt das angegebene Skript im lokalen Bereich aus (Eingabe eines Punkts vor dem Befehl), sodass die 
    vom Skript erstellten Funktionen und Variablen in der aktuellen Sitzung 
    verfügbar sind. Geben Sie den Skriptdateipfad und mögliche Parameter ein. 
    File muss der letzte Parameter im Befehl sein, da alle Zeichen, 
    die nach dem File-Parameternamen eingegeben werden, als Skriptdateipfad 
    gefolgt von den Skriptparametern interpretiert werden. 

三:作爲cdarke已經評論,最好使用列表,而不是一個字符串作爲參數傳遞給POPEN。這種方式不需要擔心Windows上的CommandLine parsing

總而言之,這應該是一條路。 (測試用的小型測試腳本。)

import subprocess 
autom = r"C:\Users\mrmostacho\Desktop\Robot\Autom.ps1" 
powershell = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" 
subprocess.Popen([powershell,"-ExecutionPolicy","Unrestricted","-File", autom]) 

如果你需要傳遞參數給腳本,像這樣做:

subprocess.Popen([powershell,"-ExecutionPolicy","Unrestricted","-File", autom, 'arg 1', 'arg 2'])