[英]Detemine if python script is called as subprocess and passing args
我有一个脚本,可以选择在完成后运行第二个脚本。 我想知道第二个脚本是否有一个好的方法来知道它是单独运行还是作为子进程运行。 如果它被称为子进程,则将args传递给第二个脚本。
第一个脚本的结尾如下:
dlg = wx.MessageDialog(None, "Shall we format?",'Format Files',wx.YES_NO | wx.ICON_QUESTION)
result = dlg.ShowModal()
if result == wx.ID_YES:
call("Threading.py", shell=True)
else:
pass
第二个脚本是一个独立脚本,它接收3个文件并将它们格式化为一个文件。 args只需在第二个脚本中设置文件名。
所以我会检索与父进程的PID os.getppid()
然后把它传递给子如使用参数Popen
:
(parent.py)
#!/usr/bin/env python
import sys
import os
from subprocess import Popen, PIPE
output = Popen(['./child.py', str( os.getppid() )], stdout=PIPE)
print output.stdout.read()
和
(child.py)
#!/usr/bin/env python
import sys
import os
parent_pid = sys.argv[1]
my_pid = str(os.getppid())
print "Parent is %s child is %s " % ( parent_pid, my_pid )
所以当你从父母那里给孩子打电话时
$ ./parent.py
Parent is 72297 child is 72346
此时很容易进行比较并检查pid。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.