2017-05-28 397 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'])