子进程返回码中的 Python 'return not' 语句

标签 python return subprocess popen return-code

我刚刚在 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 yields True if its argument is false, False otherwise.

如果self.myReturnCode 是真值,not self.myReturnCodeFalse,反之亦然。请注意,self.myReturnCode 可以是任何 Python 值,但 总是 返回一个 bool 值,True错误

如果externalProcessPopen.returncode是一个外部进程的返回码,那么如果进程出错退出则为正整数,如果退出则为0成功地。这称为 process exit status ;返回什么非零值完全取决于过程。 not 0 则为 Truenot 1(或更高的整数值)则为 False

如果是None,那么也会返回True(not NoneTrue),但是 subprocess.Popen() 返回代码是 only None 如果进程还没有退出。

关于子进程返回码中的 Python 'return not' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839849/

相关文章:

python - Python 中 Perl 模块 List::Util、List::MoreUtils 功能的类似物

python - 机器学习: working with array of objects in preprocessing

c# - “not all code path return a value”错误在方法中发生,但我确实使用了一些if语句来覆盖所有情况

python - 如何在 python 中获取命令输出而不是子进程?

python - 为什么 subprocess.Popen 不起作用

python - Beautifulsoup 解析 html 换行符

python - 递归或迭代函数 (Python)

javascript - 如何从另一个函数调用使用 window.onload 的函数

c# - 错误 : returns void, return 关键字后面不能跟对象表达式

Python Subprocess call() 不执行shell命令