【问题标题】:Checking if subprocess call executed successfully检查子进程调用是否成功执行
【发布时间】:2013-11-14 07:17:10
【问题描述】:

所以我仍在自学 Python,我想为我的服务器创建一个小脚本,它会告诉我我的 HDD 是否已挂载,以及在我登录时是否为我挂载它。(我有它在 @987654321 @)。

我面临的问题是这样的:

try:
    with open('/media/Hitachi/mountfile.txt', 'r') as f:
        print(f.readline())
except:
        print('HDD is not mounted')
        if not os.path.exists('/media/Hitachi/media'):
                print('Attempting to mount HDD')
                script = subprocess.call('mountscript.sh', shell=True)

我如何知道mountscript.sh 是否成功?

【问题讨论】:

  • iirc subprocess.call 返回退出代码.. 所以你可以检查是否 script==0 ?

标签: python subprocess


【解决方案1】:

subprocess.call 方法返回进程的returncode,以便您检查调用是否成功。

>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1

【讨论】:

    【解决方案2】:

    为什么不使用简单的 if/else 语句并使用 check_call

    if os.path.exists('/media/Hitachi/mountfile.txt'):
        print("it's mounted")
    else:
        print('HDD is not mounted')
        if not os.path.exists('/media/Hitachi/media'):
            print('Attempting to mount HDD')
            script = subprocess.check_call(['mountscript.sh','2>file.txt'], shell=True)
    

    不管怎样,故事的寓意是不要忘记 subprocess.call() 或 check_call() 的命令参数周围的括号

    【讨论】:

    • 因为我正在尝试自学其他方法,所以即使这不那么简单,它也是我自己的学习练习。
    • “try-expect 结构仅用于处理模块可以抛出的异常。它不应该用作 if-else 的替代方案。” learnpythonthehardway.org/book/ex48.html
    • 谢谢 :),顺便说一句,有没有办法将我遇到的 unix 错误通过管道传输到文本文件中?
    • ... 这可能无法按预期工作,或者至少是不好的风格:如果您使用shell=True,您应该使用字符串,而不是字符串列表。最好是with open("file.txt", "w") as f: script = subprocess.check_call(['mountscript.sh'], stderr=f)
    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2011-04-17
    相关资源
    最近更新 更多