【问题标题】:Execute a powershell file with an absolute path that contains spaces使用包含空格的绝对路径执行 powershell 文件
【发布时间】:2018-03-05 12:52:11
【问题描述】:

我正在尝试在我的 python 脚本中执行 ps1 文件。

proc = subprocess.Popen(["powershell.exe", 'F:/FOLDER/FOLDER OK/myfile.ps1'])

它停在F:/FOLDER/FOLDER,所以我添加了额外的引号,如下所示:

proc = subprocess.Popen(["powershell.exe", '"F:/FOLDER/FOLDER OK/myfile.ps1"'])

现在没有错误,但它也没有执行脚本... 有什么想法吗?

【问题讨论】:

  • windows 有时很糟糕。您是否尝试过以下解决方法:proc = subprocess.Popen(["powershell.exe", 'myfile.ps1'],cwd='F:/FOLDER/FOLDER OK')
  • @Mark - 绝对相关,但不重复。
  • @Jean-FrançoisFabre 不起作用:/ 没有错误,只是没有执行文件
  • @JeffZeitlin 答案就在那里。使用-File 就可以了。这不是 Python 特有的问题,也不是看起来的任何问题。

标签: python powershell subprocess


【解决方案1】:

powershell.exe 不假定参数自动是要执行的文件;您需要识别所有参数。使用-File 开关

proc = subprocess.Popen(["powershell.exe", "-File", r"F:\FOLDER\FOLDER OK\myfile.ps1"])

r"..."(用于raw)中的r 关闭转义序列处理,以便\ 可以在不转义的情况下使用。

请参阅 Microsoft Docs 中的 PowerShell Command Line Help

PowerShell[.exe]
       [-Command { - | <script-block> [-args <arg-array>]
                     | <string> [<CommandParameters>] } ]
       [-EncodedCommand <Base64EncodedCommand>]
       [-ExecutionPolicy <ExecutionPolicy>]
       [-File <FilePath> [<Args>]]
       [-InputFormat {Text | XML}] 
       [-Mta]
       [-NoExit]
       [-NoLogo]
       [-NonInteractive] 
       [-NoProfile] 
       [-OutputFormat {Text | XML}] 
       [-PSConsoleFile <FilePath> | -Version <PowerShell version>]
       [-Sta]
       [-WindowStyle <style>]

【讨论】:

  • 顺便说一句:PowerShell Core 现在 defaults-File,(认为明确无误;更改是必要的支持Unix shebang 行)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-07
  • 2012-05-09
  • 1970-01-01
  • 2014-05-19
  • 2015-11-08
  • 2010-12-12
相关资源
最近更新 更多