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

Python 使用 subprocess 调用外部命令行程序报错

  •  
  •   ShihanW · 87 天前 · 1035 次点击
    这是一个创建于 87 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请问一下大家,我使用 python 编写了一个命令行工具,打包成.exe 后,已经将路径写入系统环境变量里了,在 cmd 里能全局调用,但是在另一个 pyhton 代码里使用 subprocess.check_ouput 调用这个工具,却报错了:returned non-zero exit status 1 这是什么原因导致的啊

    python 版本:2.7 系统:winwos 10

    8 条回复    2024-02-01 19:38:34 +08:00
    McZoden
        1
    McZoden  
       87 天前
    先把 stderr 重定向到 stdout 里,看一下是程序内部报错,还是环境问题,
    参考:
    https://stackoverflow.com/questions/16198546/get-exit-code-and-stderr-from-subprocess-call

    shell=True 可能不需要,根据你原先代码来改

    ```
    try:
    output = subprocess.check_output(
    cmnd, stderr=subprocess.STDOUT, shell=True, timeout=3,
    universal_newlines=True)
    except subprocess.CalledProcessError as exc:
    print("Status : FAIL", exc.returncode, exc.output)
    else:
    print("Output: \n{}\n".format(output))
    ```
    ShihanW
        2
    ShihanW  
    OP
       87 天前
    @McZoden
    哈喽, 我原先的代码就两行
    ```
    cmd = "updateDoc -h"
    result = subprocess.check_output(command, shell=True)
    ```
    参照你给的修改示例,还是报错,这段代码是作为脚本在其他软件里调用的,不知道是不是版本不对,还提示没有 timeout 这个参数
    McZoden
        3
    McZoden  
       87 天前
    2.7 的版本比较旧了,其他信息比较少,只能一步一步调试
    先改成试试看吧,有没有什么其他的输出

    cmd = "updateDoc -h"
    result = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
    McZoden
        4
    McZoden  
       87 天前
    另外也可以试试 shell=False
    ShihanW
        5
    ShihanW  
    OP
       87 天前
    我在 2.7 版的 IDLE 里运行了上述代码,可以正常输出 subprocees.chek_output 结果,看起来问题是宿主程序导致的,非常感谢你的回复
    julyclyde
        6
    julyclyde  
       86 天前
    你可以在 subprocess 里输出一下 PATH 环境变量看看
    应该是你 export 给 python ,但是 python 并没有进一步 export 给 subprocess 导致的吧
    ShihanW
        7
    ShihanW  
    OP
       86 天前
    @julyclyde 我重启宿主程序后,莫名就能运行了😂
    julyclyde
        8
    julyclyde  
       86 天前
    @ShihanW 那可能是你没明白环境变量只能继承而无法活体/横向传染注入这个限制?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   875 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 21:32 · PVG 05:32 · LAX 14:32 · JFK 17:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.