退出用Popen启动的bash shell?

时间:2015-02-16 00:27:55

标签: python windows bash subprocess popen

我无法弄清楚如何关闭通过bash启动的Popen shell。我在Windows上,并试图自动化一些ssh的东西。通过git附带的bash shell更容易实现 ,因此我通过Popen以下列方式调用它:

p = Popen('"my/windows/path/to/bash.exe" | git clone or other commands') 
p.wait() 

问题是,在bash运行我输入的命令后,它不会关闭。它保持打开状态,导致wait无限期阻止。

我试过过"退出"命令最后,但它不起作用。

p = Popen('"my/windows/path/to/bash.exe" | git clone or other commands && exit') 
p.wait() 

但是,等待时无限阻挡。完成任务后,它只是在bash提示符处做任何事情。我该怎么强迫它关闭?

2 个答案:

答案 0 :(得分:1)

尝试Popen.terminate()这可能有助于杀死您的进程。如果您只有同步执行命令,请尝试直接使用subprocess.call()

例如

import subprocess
subprocess.call(["c:\\program files (x86)\\git\\bin\\git.exe",
                     "clone",
                     "repository",
                     "c:\\repository"])
0

以下是使用管道的示例,但对于大多数用例来说这有点过于复杂,只有当您与需要交互的服务交谈时才有意义(至少在我看来)。

p = subprocess.Popen(["c:\\program files (x86)\\git\\bin\\git.exe", 
                      "clone",
                      "repository",
                      "c:\\repository"],
                      stdout=subprocess.PIPE,
                      stderr=subprocess.PIPE
                     )
print p.stderr.read()
fatal: destination path 'c:\repository' already exists and is not an empty directory.
print p.wait(
128

这也可以应用于ssh

答案 1 :(得分:0)

要终止进程树,您可以use taskkill command on Windows

Popen("TASKKILL /F /PID {pid} /T".format(pid=p.pid))

作为@Charles Duffy said,您的bash使用不正确。

要使用bash运行命令,请使用-c参数:

p = Popen([r'c:\path\to\bash.exe', '-c', 'git clone repo'])

在简单的情况下,您可以使用subprocess.check_call代替Popen().wait()

import subprocess

subprocess.check_call([r'c:\path\to\bash.exe', '-c', 'git clone repo'])

如果bash进程返回非零状态(它表示错误),后一个命令会引发异常。

相关问题