python - 有没有办法测试Python函数或方法是否是直接从shell调用的?

标签 python invoke

添加到 rake 的列表和 PHP :有没有办法测试 Python 函数或方法是否直接从 Python shell 调用,而不是从 .py 脚本文件中调用?

例如,我想定义一个表达式 test_expr,当该表达式出现在模块“shelltest.py”中时,其行为如下,

#!/usr/bin/python
"""Module shelltest.py"""

def test_expr():
    #...

情况 (1):直接从 shell 调用时返回 True

>>> import shelltest
>>> shelltest.test_expr()
True

情况 (2):当导入到另一个模块“other.py”并在其中的代码中使用时,它会产生 False

#!/usr/bin/python
"""Module other.py"""

import shelltest

def other_func():
    # ...
    shelltest.test_expr()

依次从 shell 调用

>>> import other
>>> other.other_func()
False

最佳答案

如果您位于 shell,则 __name__ == '__main__'。 (此外,正如 Ned Batchelder 指出的那样,这只会告诉您函数的定义位置。)

您可能不想在函数内测试它 ​​- 它被用来区分模块是否被作为主程序调用。无论如何,您的函数应该以相同的方式工作,如果您需要不同的函数,您应该导入包含相同函数名称的不同模块。

做这样的事情:

if __name__ == '__main__':
   import formain as bumpf
else:
   import forscripts as bumpf

bumpf.domagic()

至于确定您是否处于网络环境中 - 在仅从网络调用的代码中执行此操作。 Python 脚本通常不会由 CGI 调用,因此这并不会真正作为用例出现。

关于python - 有没有办法测试Python函数或方法是否是直接从shell调用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176833/

相关文章:

python - 如何计算python pandas数据框中行之间的相关性

python - numpy python 中向量化特征值计算

Python 属性继承

c# - 跨线程操作WPF控件报错: cannot

c# - 加速反射调用 C#/.NET

c# - 当Bloomberg API通过C#连接到BBCOM时调用问题

python - 使用 openpyxl 时出现 "Bad magic number for file header"错误

python - 字典元素之间的欧氏距离

c# - 多线程和表单调用不同步

visual-studio - Visual Studio 2019(本身): Exception Has Been Thrown By The Target of an Invocation