【问题标题】:Can not catch os error with subprocessing无法通过子处理捕获 os 错误
【发布时间】:2018-02-23 14:29:45
【问题描述】:

有谁知道你是否可以在 python 中捕获 os 错误。我正在研究一个映射网络驱动器的脚本。 如果最终用户键入不存在的路径名称,则不会出现错误,这可能会成为问题。 我正在使用带有 python 3.6 版的 subprocess 模块以及 pycharm IDE。 如果我映射到不存在的位置,则会收到以下错误“发生系统错误 53。找不到网络路径。”

最后,我尝试使用 OSError、Exception 和 BaseException 来捕获错误。我用过的每一个都没有返回任何错误信息。

这是我正在运行的脚本示例。

def StoreInfo():
receiving = input("Enter receiving: ")
try:
    subprocess.call(r'net use y: \\' + receiving + '\\act\\rto\\transent', shell=True) #timeout=30
except OSError:
    #print("An unexpected error:" , sys.exc_info()[0])
    print(sending+"'s path does not exit!")

StoreInfo()

【问题讨论】:

  • 这是因为没有引发 python Excpetion。 “发生系统错误 53。找不到网络路径” - 这是 windows 错误,而不是 python
  • 如果您使用subprocess.check_call,它还应该为您提供进程的返回码,大多数以0 表示成功退出,任何其他数字表示各种错误情况,但@YaroslavSurzhikov 是正确的,没有python 错误由这个引起的,这就是为什么你不能抓住它。

标签: python python-3.x error-handling subprocess try-except


【解决方案1】:

Python » 文档Subprocess

try: 
    retcode = call("mycmd" + " myarg", shell=True) 
    if retcode < 0: 
        print >>sys.stderr, "Child was terminated by signal", -retcode 
    else: 
        print >>sys.stderr, "Child returned", retcode 
except OSError as e: 
    print >>sys.stderr, "Execution failed:", e

【讨论】:

    猜你喜欢
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多