python 在 teed 时无法分离进程。如何跨后台进程并立即退出?

发布于 2024-12-02 08:23:49 字数 2575 浏览 1 评论 0原文

我从一个简单的测试用例开始:

cat foo2.py
#!/usr/bin/python
import subprocess, sys, os

def alert():
    subprocess.Popen ("xterm &", shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

if __name__ == "__main__":

   print "hello"
   alert ()
   os._exit (0)

当我定期在命令行上运行该代码时,它会起作用:

./foo2.py

返回 unix 提示符,并且 xterm 在后台运行。

但是,当我使用 tee 运行该代码时,

./foo2.py | tee my.log

在关闭 xterm 之前我不会收到 unix 提示符。

如何让 python 脚本退出,但保持 xterm 在后台运行?

我见过: Python 生成子进程,分离,并退出以及那里提到的活动状态配方。我使用该代码创建了一个简单的测试用例,该测试用例仅在后台打开一个 xterm:

cat foo.py
#!/usr/bin/python
import subprocess, sys, os

def alert():
    subprocess.Popen ("xterm &", shell=True, stdin=None, stdout=None, stderr=None)

def createDaemon():
   """Detach a process from the controlling terminal and run it in the
   background as a daemon.
   """
   try:
      pid = os.fork()   # Fork a first child.
   except OSError, e:
      raise Exception, "%s [%d]" % (e.strerror, e.errno)

   if (pid == 0):   # The first child.
      os.setsid()
      try:
         pid = os.fork()    # Fork a second child.
      except OSError, e:
         raise Exception, "%s [%d]" % (e.strerror, e.errno)

      if (pid == 0):    # The second child.
     alert () 
      else:
         os._exit(0)    # Exit parent (the first child) of the second child.
   else:
      os._exit(0)   # Exit parent of the first child.

   # Close all open file descriptors.  This prevents the child from keeping
   import resource      # Resource usage information.
   maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
   if (maxfd == resource.RLIM_INFINITY):
      maxfd = 1024

   # Iterate through and close all file descriptors.
   for fd in range(0, maxfd):
      try:
         os.close(fd)
      except OSError:   # ERROR, fd wasn't open to begin with (ignored)
         pass

   os.open(REDIRECT_TO, os.O_RDWR)  # standard input (0)
   os.dup2(0, 1)            # standard output (1)
   os.dup2(0, 2)            # standard error (2)

   return(0)

if __name__ == "__main__":

   print "hello"
   retCode = createDaemon()

   sys.exit (0)

当我定期在命令行上运行该代码时,它会起作用:

./foo.py

返回 unix 提示符,并且 xterm 在后台运行。

但是,当我使用 tee 运行该代码时,

./foo.py | tee my.log

在关闭 xterm 之前我不会收到 unix 提示符。

如何让 python 脚本退出,但保持 xterm 在后台运行?

I started with a simple testcase:

cat foo2.py
#!/usr/bin/python
import subprocess, sys, os

def alert():
    subprocess.Popen ("xterm &", shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

if __name__ == "__main__":

   print "hello"
   alert ()
   os._exit (0)

When I run that code on the command line regularly, it works:

./foo2.py

returns the unix prompt, and the xterm is running in the background.

However, when I run that code with a tee

./foo2.py | tee my.log

I do not get the unix prompt until I close the xterm.

How can I get the python script to exit, but keep the xterm running in the background?

I've seen: Python spawn off a child subprocess, detach, and exit and the activestate recipe mentioned there. I've used that code to create a simple testcase which just opens an xterm in the background:

cat foo.py
#!/usr/bin/python
import subprocess, sys, os

def alert():
    subprocess.Popen ("xterm &", shell=True, stdin=None, stdout=None, stderr=None)

def createDaemon():
   """Detach a process from the controlling terminal and run it in the
   background as a daemon.
   """
   try:
      pid = os.fork()   # Fork a first child.
   except OSError, e:
      raise Exception, "%s [%d]" % (e.strerror, e.errno)

   if (pid == 0):   # The first child.
      os.setsid()
      try:
         pid = os.fork()    # Fork a second child.
      except OSError, e:
         raise Exception, "%s [%d]" % (e.strerror, e.errno)

      if (pid == 0):    # The second child.
     alert () 
      else:
         os._exit(0)    # Exit parent (the first child) of the second child.
   else:
      os._exit(0)   # Exit parent of the first child.

   # Close all open file descriptors.  This prevents the child from keeping
   import resource      # Resource usage information.
   maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
   if (maxfd == resource.RLIM_INFINITY):
      maxfd = 1024

   # Iterate through and close all file descriptors.
   for fd in range(0, maxfd):
      try:
         os.close(fd)
      except OSError:   # ERROR, fd wasn't open to begin with (ignored)
         pass

   os.open(REDIRECT_TO, os.O_RDWR)  # standard input (0)
   os.dup2(0, 1)            # standard output (1)
   os.dup2(0, 2)            # standard error (2)

   return(0)

if __name__ == "__main__":

   print "hello"
   retCode = createDaemon()

   sys.exit (0)

When I run that code on the command line regularly, it works:

./foo.py

returns the unix prompt, and the xterm is running in the background.

However, when I run that code with a tee

./foo.py | tee my.log

I do not get the unix prompt until I close the xterm.

How can I get the python script to exit, but keep the xterm running in the background?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

又怨 2024-12-09 08:23:49

运行nohup xterm &(使进程解耦)

Run nohup xterm & (so that the process is decoupled)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文