【问题标题】:Running external scripts in Python在 Python 中运行外部脚本
【发布时间】:2014-05-14 05:59:28
【问题描述】:

我正在尝试使用 subprocess.call 运行 PowerShell 脚本,但运气不佳。

subprocess.call(['.\ConvertPPTtoImage.ps1', path+'file.pptx'])

直接从 PowerShell 运行 .\ConvertPPTtoImage.ps1 file.pptx 工作正常,但上面的行只是在记事本中打开 ConvertPPTtoImage.ps1。我尝试了其他变体(从一开始就删除 .\,删除 shell=True,使用 os.system 而不是 subprocess.call)并遇到崩溃或 WindowsError: [Error 193] %1 is not a valid Win32 application

这样做的正确方法是什么?

【问题讨论】:

    标签: python windows python-2.7 powershell subprocess


    【解决方案1】:

    主要在 linux 机器上工作,这是我最好的猜测。听起来ConvertPPTtoImage.ps1 是一个脚本,然后由 powershell 运行。该命令正在尝试(a)使用ps1文件的默认程序运行它,这将在记事本中打开它,或者(b)作为本身的可执行文件,由于文本文件本身不是可执行文件而失败。解决方案是按如下方式替换调用。

    subprocess.call([r'C:\path\to\powershell.exe',r'.\ConvertPPTtoImage.ps1',path+'file.pptx'])
    

    也就是说,使用参数调用 powershell 来告诉它要运行哪个脚本。

    附带说明,每当在 python 中使用 Windows 路径时,我建议在每个字符串的开头放置一个 r,这告诉 python 忽略转义序列。由于 python 的转义字符和 Window 的路径分隔符都是反斜杠,这样可以省去很多麻烦。

    【讨论】:

      【解决方案2】:

      您需要调用 PowerShell 可执行文件本身。默认情况下,Windows 将在记事本或您选择的其他文本编辑器中打开 .ps1 文件。默认情况下,它们不使用 PowerShell 作为安全功能运行。

      powershell.exe -ExecutionPolicy Bypass -File c:\path\to\ConvertPPTtoImage.ps1 c:\path\to\file.pptx
      

      【讨论】:

        猜你喜欢
        • 2011-05-26
        • 1970-01-01
        • 2015-10-01
        • 2018-08-14
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多