python - 如何仅执行另一个文件中的特定函数

标签 python python-2.7 python-import

我有两个文件:

test2.py:

def fun():
    print "from fun"
print  "from test2"

test.py:

from test2 import fun
print "in text"
fun()

我只想执行 test2.py 中的 fun 函数,但我也从 test2 中获取了 fun 函数.

如何才能只使用我想要的功能?

最佳答案

test2.py 中,您需要确保仅在程序自行运行时打印“from test2”。

你可以这样做:

test2.py

def fun():
    print "from fun"

if __name__ == "__main__":
    print  "from test2"

关于python - 如何仅执行另一个文件中的特定函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40449016/

相关文章:

Python数学公式计算

python - 使用 Python/Sklearn 创建并拟合乘法线性回归

Python如何在不删除已有内容的情况下继续写入文件

python - 在 Python2.7.9 的形式源安装后我得到 ssl.SSLError : [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl. c:581)

python - 如何将函数作为变量运行?

python - 使用 apply 将从一列(具有 json 类型)提取的值插入到另一列

python - 按时计算后在数据框中添加新列

python - `python -m foo.bar` 与 `python foo/bar.py` 本地导入

python-3.x - 根据另一个模块是否存在为模块使用多个别名

Python - os.path 不存在 : AttributeError: 'module' object has no attribute 'path'