Python 退出由Popen启动的bash shell?

Python 退出由Popen启动的bash shell?,python,windows,bash,subprocess,popen,Python,Windows,Bash,Subprocess,Popen,我不知道如何关闭通过Popen启动的bashshell。我在windows上,正在尝试自动化一些ssh内容。通过git附带的bashshell可以更容易地实现这一点,因此我通过Popen以以下方式调用它: p = Popen('"my/windows/path/to/bash.exe" | git clone or other commands') p.wait() 问题是,bash运行我传入的命令后,它不会关闭。它保持打开状态,导致我的等待无限期阻塞 我尝试在最后串接一个“exit”命令

我不知道如何关闭通过
Popen
启动的
bash
shell。我在windows上,正在尝试自动化一些ssh内容。通过git附带的
bash
shell可以更容易地实现这一点,因此我通过
Popen
以以下方式调用它:

p = Popen('"my/windows/path/to/bash.exe" | git clone or other commands') 
p.wait() 
问题是,bash运行我传入的命令后,它不会关闭。它保持打开状态,导致我的
等待
无限期阻塞

我尝试在最后串接一个“exit”命令,但它不起作用

p = Popen('"my/windows/path/to/bash.exe" | git clone or other commands && exit') 
p.wait() 
但是,仍然有无限的阻塞等待。在完成任务后,它只是坐在bash提示符旁,什么也不做。我如何强制它关闭

尝试
Popen.terminate()
这可能有助于终止进程。如果只有同步执行命令,请尝试将其直接用于
subprocess.call()

比如说

import subprocess
subprocess.call(["c:\\program files (x86)\\git\\bin\\git.exe",
                     "clone",
                     "repository",
                     "c:\\repository"])
0
下面是一个使用管道的示例,但对于大多数用例来说,这有点过于复杂,只有在您与需要交互的服务交谈时(至少在我看来)才有意义


这也可以应用于ssh

要终止进程树,您可以:

例如,您的bash用法不正确

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

p = Popen([r'c:\path\to\bash.exe', '-c', 'git clone repo'])
在简单的情况下,您可以使用
子流程。check_call
而不是
Popen().wait()


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

这里的
|
字符是怎么回事?这不是向bash传递命令的方式,还有,为什么要调用bash,而不是直接从Python调用git命令?直接路由使信号处理变得更容易——这意味着您可以轻松地检查git命令本身的状态或终止git命令本身,而不仅仅是在bash shell上有一个句柄,而无法知道git(或其下的其他子进程)在做什么。@CharlesDuffy这是在bashPopen中管道命令的方式(['/path/to/bash.exe','-c',command;command;command']是的,这是您在bash中设置管道的方式,但您不会通过将shell的输出管道化到该命令来在shell中运行命令。
bash | git clone
获取
bash
的输出,并将其作为
git clone
的输入发送,但是
git clone
不会从stdin读取,bash只会坐在那里等待输入这种用法,这就是为什么您会在这里抱怨“wait()”的行为。
p.terminate()
会有所帮助,是的,但是考虑到这里显示的用法,您也可以解决命令总是挂起的原因。
subprocess.call()
相反,如果
p.wait()
挂起,则总是挂起。
Popen("TASKKILL /F /PID {pid} /T".format(pid=p.pid))
p = Popen([r'c:\path\to\bash.exe', '-c', 'git clone repo'])
import subprocess

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