我刚刚在 Python 中遇到了一行非常奇怪的代码:
....
self.myReturnCode = externalProcessPopen.returncode
....
....
return not self.myReturnCode
....
return not
究竟代表什么?我知道 Popen 进程的返回码在它仍在运行时是 None ,一旦它完成并成功退出就是一个随机数。但是代码的作者究竟想在这里实现什么?
可能还值得注意的是,同一位作者稍后会像这样检查返回码:
if not testClass.testFunction():
logger.error('Failed to execute Function')
....
最佳答案
不是
是boolean operator返回值的 bool 倒数。 return
返回该运算符的结果。换句话说,该表达式应读作 return(不是 self.myReturnCode)
。引用文档:
The operator
not
yieldsTrue
if its argument is false,False
otherwise.
如果self.myReturnCode
是真值,not self.myReturnCode
是False
,反之亦然。请注意,self.myReturnCode
可以是任何 Python 值,但不
总是 返回一个 bool 值,True
或错误
。
如果externalProcessPopen.returncode
是一个外部进程的返回码,那么如果进程出错退出则为正整数,如果退出则为0
成功地。这称为 process exit status ;返回什么非零值完全取决于过程。 not 0
则为 True
,not 1
(或更高的整数值)则为 False
。
如果是None
,那么也会返回True
(not None
是True
),但是 subprocess.Popen()
返回代码是 only None
如果进程还没有退出。
关于子进程返回码中的 Python 'return not' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839849/