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



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

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

第一个例子:

echo -e "a = 1ndef 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 = 1ndef 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

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

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

echo -e "a = 1ndef 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

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

过了一秒钟,我发布了我的问题,我想到了执行函数。这就是我的解决方案:

# 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的规则,如果违反,我将删除这篇文章。