[英]Python 'return not' statement in subprocess returncode
我在Python中遇到了一段非常奇怪的代碼:
....
self.myReturnCode = externalProcessPopen.returncode
....
....
return not self.myReturnCode
....
什么return not
什么? 我知道Popen進程的返回碼在它仍在運行時為None,一旦完成並成功退出,則為隨機數。 但是代碼的作者究竟想要在這里實現什么呢?
也許值得注意的是,同一作者稍后會檢查返回代碼,如下所示:
if not testClass.testFunction():
logger.error('Failed to execute Function')
....
not
是一個布爾運算符 ,返回值的布爾反轉。 return
返回該運算符的結果。 換句話說,表達式應該被讀作return (not self.myReturnCode)
。 引用文檔:
如果參數為false,則運算符
not
產生True
,否則返回False
。
如果self.myReturnCode
是一個真值,則not self.myReturnCode
為False
,反之亦然。 請注意, self.myReturnCode
可以是任何Python值,但not
總是返回一個布爾值,無論是True
還是False
。
如果externalProcessPopen.returncode
是外部進程的返回代碼,那么如果進程退出並出現錯誤,則它將是正整數,如果退出成功,則為0
。 這稱為流程退出狀態 ; 返回的非零值完全取決於進程。 not 0
然后是True
, not 1
(或更高的整數值)給你False
。
如果為None
,則返回True
( not None
為True
),但如果進程尚未退出,則subprocess.Popen()
返回代碼僅為 None
。
return not self.myReturnCode
應解釋為:
return (not self.myReturnCode)
它在你的代碼中做的只是這樣:
0
則返回True
0
則返回False
。 它不是隨機數,它是外部進程的返回碼,其中0表示成功,非零數表示失敗。
因此返回not self.myReturnCode
意味着它在進程成功時返回True
而在進程指示失敗時返回False
。
return not self.myReturnCode
相當於:
return False if self.myReturnCode else True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.