将 python 代码在 运行 一部分之后移动到后台
Move python code to background after running a part of it
我有一个 python 代码,它有一些部分需要 运行 在前台,因为它告诉我们套接字连接是否正确。现在在 运行 之后,输出被写入文件。
有没有办法在运行在前台执行一些确定的步骤后,自动将运行ning python 代码(进程)从前台移动到后台,以便我可以继续我在终端上的工作。
我知道使用 screen
是一种选择,但还有其他方法吗?由于 运行 在前台显示一个部分后,终端中不会显示任何输出,我不想 运行 不必要地屏幕。
如果您有 #!/bin/env python,并且其权限设置正确,您可以尝试 nohup /path/to/test.py &
在 python 中,您可以从当前终端分离,注意这仅适用于类 UNIX 系统:
# Foreground stuff
value = raw_input("Please enter a value: ")
import os
pid = os.fork()
if pid == 0:
# Child
os.setsid() # This creates a new session
print "In background:", os.getpid()
# Fun stuff to run in background
else:
# Parent
print "In foreground:", os.getpid()
exit()
在 Bash 中,您实际上只能以交互方式做事。当您希望将 python 进程置于后台时,请使用 CTRL+Z(前导 $
是通用 bash 提示符的约定):
$ python gash.py
Please enter a value: jjj
^Z
[1]+ Stopped python gash.py
$ bg
[1]+ python gash.py &
$ jobs
[1]+ Running python gash.py &
请注意,在 python 代码中使用 setsid()
将 不会 显示 jobs
中的进程,因为后台作业管理是由shell,而不是 python.
我有一个 python 代码,它有一些部分需要 运行 在前台,因为它告诉我们套接字连接是否正确。现在在 运行 之后,输出被写入文件。
有没有办法在运行在前台执行一些确定的步骤后,自动将运行ning python 代码(进程)从前台移动到后台,以便我可以继续我在终端上的工作。
我知道使用 screen
是一种选择,但还有其他方法吗?由于 运行 在前台显示一个部分后,终端中不会显示任何输出,我不想 运行 不必要地屏幕。
如果您有 #!/bin/env python,并且其权限设置正确,您可以尝试 nohup /path/to/test.py &
在 python 中,您可以从当前终端分离,注意这仅适用于类 UNIX 系统:
# Foreground stuff
value = raw_input("Please enter a value: ")
import os
pid = os.fork()
if pid == 0:
# Child
os.setsid() # This creates a new session
print "In background:", os.getpid()
# Fun stuff to run in background
else:
# Parent
print "In foreground:", os.getpid()
exit()
在 Bash 中,您实际上只能以交互方式做事。当您希望将 python 进程置于后台时,请使用 CTRL+Z(前导 $
是通用 bash 提示符的约定):
$ python gash.py
Please enter a value: jjj
^Z
[1]+ Stopped python gash.py
$ bg
[1]+ python gash.py &
$ jobs
[1]+ Running python gash.py &
请注意,在 python 代码中使用 setsid()
将 不会 显示 jobs
中的进程,因为后台作业管理是由shell,而不是 python.