蟒蛇: os.spawn 。无法在后台启动 bash 进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12759551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:28:50  来源:igfitidea点击:

python: os.spawn . cannot start bash process on background

pythonbash

提问by Daniel Gurianov

Task is to execute bash script from python script and let it execute on background, even if python script will finish. I need UNIX solution and i do not care if it will be not working on Win.

任务是从 python 脚本执行 bash 脚本并让它在后台执行,即使 python 脚本将完成。我需要 UNIX 解决方案,我不在乎它是否不适用于 Win。

Python script :

Python脚本:

#!/usr/bin/env python
import os, commands
command = '/usr/bin/ssh localhost "/home/gd/test/python/back.sh  "   '
print os.spawnlp(os.P_NOWAIT,command)
print "Python done"

/home/gd/test/python/back.sh :

/home/gd/test/python/back.sh :

#!/usr/bin/bash

/bin/echo "started"
/bin/sleep 80
/bin/echo "ended"

The issue is, when python script starts , i see PID of spawned process printed. But there is no process on background. When i use P_WAIT i see exit code 127 which means that command not found in the path. But i already provided all paths that already possible? These scripts works perfectly with commands.getouput.

问题是,当 python 脚本启动时,我看到打印的生成进程的 PID。但是后台没有进程。当我使用 P_WAIT 时,我看到退出代码 127,这意味着在路径中找不到该命令。但是我已经提供了所有可能的路径?这些脚本与 commands.getouput 完美配合。

回答by John La Rooy

Something like this should work

这样的事情应该工作

#!/usr/bin/env python
import os
command = ['/usr/bin/ssh', 'ssh', 'localhost', '/home/gd/test/python/back.sh']
print os.spawnlp(os.P_NOWAIT, *command)
print "Python done"

Note that it's preferable to use the subprocessmodule here instead of spawn

请注意,这里最好使用subprocess模块而不是 spawn

#!/usr/bin/env python
from subprocess import Popen
command = ['/usr/bin/ssh', 'localhost', '/home/gd/test/python/back.sh']
print Popen(command)
print "Python done"