【问题标题】:Subprocess opens PowerShell, runs commands, then dies子进程打开 PowerShell,运行命令,然后死掉
【发布时间】:2019-06-23 01:36:17
【问题描述】:

我编写了一些代码,使用 Python subprocess 模块打开 PowerShell 窗口,然后在同一窗口中运行命令。 PS 窗口打开,然后几乎立即关闭。如果我从cmd 中删除了第二项,下面的代码将打开一个 PS 窗口并保持打开状态。

import subprocess
cmd = ['powershell', 'ls']
prompt = subprocess.Popen(cmd, stdin=subprocess.PIPE)

【问题讨论】:

    标签: python python-2.7 powershell subprocess


    【解决方案1】:

    添加-noexit参数如下(-noprofile不是强制性的):

    import subprocess
    cmd = ['powershell', '-noprofile', '-noexit', '&', 'ls *.csv']
    prompt = subprocess.call ( cmd )
    

    结果

    【讨论】:

      【解决方案2】:

      有什么理由不使用subprocess.call 代替吗?我认为它会做你想要的。

      【讨论】:

        【解决方案3】:

        因为你忘了communicate 处理 只需添加一行

        output, error = prompt.communicate()  # this is to start the process
        print(output) # add stdout=subprocess.PIPE
        print(error)  # add stderr=subprocess.PIPE
        

        PS:我不能帮你用powershell,因为我不知道powershell

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多