私は簡単なテストケースから始めました:
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はバックグラウンドで実行されています。
ただし、そのコードをTシャツで実行すると
./foo2.py | tee my.log
xtermを閉じるまでunixプロンプトが表示されません。
Pythonスクリプトを終了させながら、xtermをバックグラウンドで実行し続けるにはどうすればよいですか?
私が見たのは、Pythonが子サブプロセスを生成し、デタッチして終了し、そこで言及されているactivestateレシピです。そのコードを使用して、バックグラウンドで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はバックグラウンドで実行されています。
ただし、そのコードをTシャツで実行すると
./foo.py | tee my.log
xtermを閉じるまでunixプロンプトが表示されません。
Pythonスクリプトを終了させながら、xtermをバックグラウンドで実行し続けるにはどうすればよいですか?