首页 文章

退出用Popen启动的bash shell?

提问于
浏览
-2

我无法弄清楚如何关闭通过 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运行我输入的命令后,它不会关闭 . 它保持打开状态导致我的 wait 无限期阻止 .

我已经尝试在最后串起一个“退出”命令,但它不起作用 .

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

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

2 回答

  • 0

    试试 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

    要终止进程树,你可以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 进程返回非零状态(它表示错误),后一个命令会引发异常 .

相关问题