启动一个完全独立的过程 [英] Launch a completely independent process

查看:83
本文介绍了启动一个完全独立的过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的python脚本 main.py 启动一个进程。具体来说,我想运行以下命令:

I want to initiate a process from my python script main.py. Specifically, I want to run the below command:

`nohup python ./myfile.py &`

和文件 myfile.py 应该继续运行,即使在 main.py 脚本退出。

and the file myfile.py should continue running, even after the main.py script exits.

我也希望获得 pid

I also wish to get the pid of the new process.

我尝试过:


  • os.spawnl *

  • os.exec *

  • 子进程。Popen

  • os.spawnl*
  • os.exec*
  • subprocess.Popen

都终止了 myfile.py main.py 脚本退出时。

and all are terminating the myfile.py when the main.py script exits.

更新:我可以在 xdg-open中使用 os.startfile 吗?

Update: Can I use os.startfile with xdg-open? Is it the right approach?

示例

a = subprocess.Popen([sys.executable, "nohup /usr/bin/python25 /long_process.py &"],\
     stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
print a.pid

如果我检查 ps aux | grep long_process ,没有进程在运行。

If I check ps aux | grep long_process, there is no process running.

long_process.py ,它会继续打印一些文本:不退出

long_process.py which keeps on printing some text: no exit.

我在这里做错什么了吗?

Am I doing anything wrong here?

推荐答案

您打开您长期运行的过程,并保留一个管道。因此,您希望与其交谈。当启动器脚本退出时,您将无法与其进行对话。 长时间运行的进程收到 SIGPIPE 并退出。

You open your long-running process and keep a pipe to it. So you expect to talk to it. When yor launcher script exits, you can no longer talk to it. The long-running process receives a SIGPIPE and exits.

下面的代码才起作用对我来说(Linux,Python 2.7)。

The following just worked for me (Linux, Python 2.7).

创建一个长时间运行的可执行文件:

Create a long-running executable:

$ echo "sleep 100" > ~/tmp/sleeper.sh

运行Python REPL:

Run Python REPL:

$ python
>>>

import subprocess
import os
p = subprocess.Popen(['/bin/sh', os.path.expanduser('~/tmp/sleeper.sh')])
# look ma, no pipes!
print p.pid
# prints 29893

退出REPL并查看进程仍在运行:

Exit the REPL and see the process still running:

>>> ^D
$ ps ax | grep sleeper
29893 pts/0    S      0:00 /bin/sh .../tmp/sleeper.sh
29917 pts/0    S+     0:00 grep --color=auto sleeper

如果您想先与已启动的进程进行交流,然后再让它继续运行,则有几种选择:

If you want to first communicate to the started process and then leave it alone to run further, you have a few options:


  • 在长期运行的过程中处理 SIGPIPE ,不要死于此。启动程序退出后,无需stdin即可继续生活。

  • 使用参数,环境或临时文件传递您想要的任何内容。

  • 如果您想进行双向通信,请考虑使用命名管道( man mkfifo )或套接字,或编写适当的服务器

  • 在完成双向双向通信阶段后,使运行时间较长的分叉。

  • Handle SIGPIPE in your long-running process, do not die on it. Live without stdin after the launcher process exits.
  • Pass whatever you wanted using arguments, environment, or a temporary file.
  • If you want bidirectional communication, consider using a named pipe (man mkfifo) or a socket, or writing a proper server.
  • Make the long-running process fork after the initial bi-direcional communication phase is done.

这篇关于启动一个完全独立的过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆