python 脚本结束后,从 python 调用的 shell 脚本还会保留吗?
作为自动化测试的一部分,我有一个 python 脚本,需要调用两个 shell 脚本,这两个脚本启动两个不同的服务器,这两个服务器需要在调用脚本结束后进行交互。 (它实际上是一个 jython 脚本,但我现在不确定这是否重要。)我可以做什么来确保服务器在 python 脚本结束后保持正常运行?
此时它们被称为这样的:
def runcmd(str, sleep):
debug('Inside runcmd, executing: ' + str)
os.chdir("/new/dir/")
directory = os.getcwd()
print 'current dir: '+ directory
os.system(str)
t = threading.Thread(
target=runcmd,
args=( cmd, 50,)
)
As part of an automated test, I have a python script that needs to call two shell scripts that start two different servers that need to interact after the calling script ends. (It's actually a jython script, but I'm not sure that matters at this point.) What can I do to ensure that the servers stay up after the python script ends?
At this point they're called something like this:
def runcmd(str, sleep):
debug('Inside runcmd, executing: ' + str)
os.chdir("/new/dir/")
directory = os.getcwd()
print 'current dir: '+ directory
os.system(str)
t = threading.Thread(
target=runcmd,
args=( cmd, 50,)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Python线程将随着Python一起消亡。此外,os.system 正在阻塞。但这没关系——如果 os.system() 运行的命令启动一个新进程(但不是子进程),那么一切都会好起来的。例如,在 Windows 上,如果命令以“start”开头,则“start”进程将在 Python 终止后保留。
编辑:
nohup
相当于 Linux 上的start
。 (感谢 S.洛特)。Python threads will all die with Python. Also, os.system is blocking. But that's okay -- if the command that os.system() runs launches a new process (but not a child process), all will be fine. On Windows, for instance, if the command begins with "start" the "start"'d process will remain after Python dies.
EDIT:
nohup
is an equivalent tostart
on Linux. (Thanks to S. Lott).os.system()
在其启动的进程结束之前不会返回。使用subprocess
或Runtime.exec()
如果你想在一个单独的过程中。os.system()
does not return until the process it launches has ended. Usesubprocess
orRuntime.exec()
if you want it in a separate process.我想知道使用 subprocess.Popen 是否更适合您。
也许做类似 shell=True 的事情
I wonder if using subprocess.Popen would work better for you.
maybe doing something like shell=True
线程不起作用,因为它们是进程的一部分。
system
调用将不起作用,因为它在新进程执行时会阻塞。您将需要使用诸如 os.fork() 之类的东西来生成新进程并在新进程中执行它。查看 subprocess 以获得一些好的食谱风格的解决方案。
Threads won't work because they are part of the process. The
system
call won't work because it blocks as your new process executes.You will need to use something like
os.fork()
to spawn a new process and execute it in the new process. Take a look at subprocess for some good cookbook style solutions to this.通常,要启动独立于其父级的长时间运行的服务器,您需要对其进行守护进程。根据您的环境,有多种包装器可以帮助完成此过程。
Generally, to launch a long-running server that's independent of its parent, you need to daemonize it. Depending on your environment, there are various wrappers that can assist in this process.