V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
shineonme
V2EX  ›  Python

如何在一个 Python 程序中,获取运行另一个 py 文件后,返回输出到终端的内容

  •  
  •   shineonme · Oct 22, 2022 · 3147 views
    This topic created in 1285 days ago, the information mentioned may be changed or developed.

    Traceback 那部分内容,试过了 os.popen 并不能做到

    >>> import os
    >>> os.system("python3 douyu.py")
    输入斗鱼直播间号:
    114514
    Traceback (most recent call last):
      File "douyu.py", line 135, in <module>
        print(s.get_real_url())
      File "douyu.py", line 126, in get_real_url
        raise Exception('房间未开播')
    Exception: 房间未开播
    256
    
    6 replies    2022-10-25 20:34:51 +08:00
    Yourshell
        1
    Yourshell  
       Oct 22, 2022 via Android
    改写成模块 import
    或用 execfile

    感觉是个 XY 问题
    crab
        2
    crab  
       Oct 22, 2022   ❤️ 1
    pppwaw
        3
    pppwaw  
       Oct 22, 2022 via iPhone
    traceback 在 stderr 里吧,你确定你 popen 读对了么
    aijam
        4
    aijam  
       Oct 22, 2022
    直接 import douyu 就完了
    shineonme
        5
    shineonme  
    OP
       Oct 22, 2022
    @Yourshell
    @aijam 确实,直接 import 下就可以了,怎么之前脑子就没转过来呢
    zhanglintc
        6
    zhanglintc  
       Oct 25, 2022   ❤️ 1
    用`os.system()`去执行命令并试图获得输出是个常见错误。

    你得用诸如`subprocess.check_output()`的方式来获得返回(没办法就是这么繁琐)。
    当然你这里本来就是 py 文件,的确 import 运行就可以。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5138 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 09:08 · PVG 17:08 · LAX 02:08 · JFK 05:08
    ♥ Do have faith in what you're doing.