【问题标题】:How to know and prevent an error with terminal commands from python?如何知道和防止来自 python 的终端命令出错?
【发布时间】:2021-06-25 07:58:24
【问题描述】:

制作一个可以在听命令时打开应用程序的程序。应用程序名称存储在变量“a”中。然后用以下行打开:

os.system("open /Applications/" + a + ".app")

但有时系统上可能不存在“a”,例如控制台打印的“音乐”:

The file /Applications/music.app does not exist.

python 代码完全停止。

我怎么知道控制台给出了这个错误并阻止程序停止?

【问题讨论】:

    标签: python macos darwin


    【解决方案1】:

    subprocessos.system更强大,子进程的stdout和stderr可以用子进程忽略

    import subprocess
    res=subprocess.run(["open", "/Applications/" + a + ".app"])
    print(res.returncode)
    

    使用res.returncode获取执行结果(非零值表示子进程出错)。

    【讨论】:

      【解决方案2】:

      也许您可以尝试使用try/except 命令来处理python 中的错误:https://docs.python.org/3/tutorial/errors.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        • 1970-01-01
        • 1970-01-01
        • 2012-10-29
        • 1970-01-01
        • 2011-07-22
        相关资源
        最近更新 更多