[不懂就问] python subprocess 模块遇到一个疑问

2015-12-06 22:59:33 +08:00
 raingolee

Hi, 各位大哥

最近在看 python subprocess 模块的时候产生了一点疑问,因此上 V2 求助,希望得到各位帮助

问题来源:
在 Python 中利用 subprocess 很容易就能调用一个子进程,如下:

from multiprocessing import Process
import os

def subpro():
    print 'there is a sub process which pid is %s' %os.getpid()

if __name__ == '__main__':
    p=Process(target=subpro, name='process_start_test')
    p.start()
    print 'there is a parent process which pid id %s' %os.getpid()

那么从官方文档看这个模块的说明,在实例化 Process 这个类的时候如果不传入参数 target 的话,执行 start 方法会调用 Process 类里的 run 方法

但是小弟不才,琢磨了半天 subprocess 源码,愣是看不出 start 方法在没有 target 属性是如何调用 run 方法的,以下为节选 subprocess 代码

def run(self):
        '''
        Method to be run in sub-process; can be overridden in sub-class
        '''
        if self._target:
            self._target(*self._args, **self._kwargs)

    def start(self):
        '''
        Start child process
        '''
        assert self._popen is None, 'cannot start a process twice'
        assert self._parent_pid == os.getpid(), \
               'can only start a process object created by current process'
        assert not _current_process._daemonic, \
               'daemonic processes are not allowed to have children'
        _cleanup()
        if self._Popen is not None:
            Popen = self._Popen
        else:
            from .forking import Popen
        self._popen = Popen(self)
        _current_process._children.add(self)

希望能得到大家的帮助,谢谢各位观看

3203 次点击
所在节点    Python
3 条回复
SErHo
2015-12-06 23:13:46 +08:00
raingolee
2015-12-06 23:15:12 +08:00
不好意思,标题写错了,应该是 multiprocess 模块,丢人。。。
raingolee
2015-12-06 23:17:17 +08:00
@SErHo 看到了,真的非常感谢,哭

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/241590

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX