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
shineonme
V2EX  ›  Python

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

  •  
  •   shineonme · 2022-10-22 18:59:07 +08:00 · 2177 次点击
    这是一个创建于 552 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2022-10-25 20:34:51 +08:00
    Yourshell
        1
    Yourshell  
       2022-10-22 19:06:22 +08:00 via Android
    改写成模块 import
    或用 execfile

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

    你得用诸如`subprocess.check_output()`的方式来获得返回(没办法就是这么繁琐)。
    当然你这里本来就是 py 文件,的确 import 运行就可以。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1262 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 23:57 · PVG 07:57 · LAX 16:57 · JFK 19:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.