繁体   English   中英

如何从主代码继承一个函数并在模块内执行它。 (这也适用于变量)

[英]How to inherit a function from the main code and execute it inside the module. (this also applies to variables)

编辑:我找到了解决方案,如果您知道其他方式,请分享。

我有一个关于如何导入函数并让它仍然表现得像在主函数内部一样的问题。

第一个例子:

echo -e "a = 1\ndef test():\n    print(a)" > test_function.py
cat test_function.py
## output:
# a = 1
# def test():
#     print(a)
python3 -c "exec('from test_function import *'); a = -1; test()"
## output: 
# 1

我希望输出-1,但它是1。

第二个例子:

echo "test(a)" > test_function.py
cat test_function.py
## output:
# test(a)
python3 -c "exec('a = 1\ndef test(a):\n    print(a)');a = -1;from test_function import *"
## output:
# Traceback (most recent call last):
#   File "<string>", line 1, in <module>
#   File "/tmp/test_function.py", line 1, in <module>
#     test(a)
# NameError: name 'test' is not defined

我如何能够继承导入的 .py 文件中的主要变量和函数,以便我可以像在一个主文件中一样使用它们?

我知道你可以这样做,但这对我没有帮助:

echo -e "a = 1\ndef test(a):\n    print(a)" > test_function.py
cat test_function.py
## output:
# a = 1
# def test(a):
#    print(a)

python3 -c "exec('from test_function import *'); a = -1; test(a)"
## output:
# -1

我试过搜索这个问题,但我不知道如何描述这个问题。

一秒钟后,我发布了我的问题,我想到了 exec 函数。 所以这是我的解决方案:

# contents of file_with_additional_functionality.py:
function_you_want_to_call_in_the_file()
#/usr/bin/python3
# contents of main.py
def function_you_want_to_call_in_the_file:
    print('Hello from inside the main function.')
with open('file_with_additional_functionality.py') as f:
    exec(f.read())
## output:
# Hello from inside the main function.

我希望它不违反 stackoverflow 的规则,如果是的话,我将删除该帖子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM