V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
raingolee
V2EX  ›  Python

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

  •  
  •   raingolee · 2015-12-06 22:59:33 +08:00 · 3187 次点击
    这是一个创建于 3061 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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)
    

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

    3 条回复    2015-12-06 23:17:17 +08:00
    raingolee
        2
    raingolee  
    OP
       2015-12-06 23:15:12 +08:00
    不好意思,标题写错了,应该是 multiprocess 模块,丢人。。。
    raingolee
        3
    raingolee  
    OP
       2015-12-06 23:17:17 +08:00
    @SErHo 看到了,真的非常感谢,哭
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3456 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:04 · PVG 19:04 · LAX 04:04 · JFK 07:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.