2017-09-14 73 views
1

有誰知道你是否可以在python中捕獲os錯誤。我正在研究映射網絡驅動器的腳本。 如果最終用戶鍵入不存在的路徑的名稱,則不會顯示錯誤,這可能會成爲問題。 我正在使用python版本3.6的子進程模塊,以及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()

+1

,那是因爲沒有蟒蛇錯誤時拋出提高。 「系統錯誤53發生了,網絡路徑沒有找到」 - 這是windows錯誤,不是python –

+0

如果你使用'subprocess.check_call',它也應該給你進程的返回代碼,大多數情況下以0結束並退出其他數字來表示各種錯誤條件,但@ YaroslavSurzhikov是正確的,沒有提出這個python錯誤,這就是爲什麼你不能捕捉它。 –

回答

0

的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