我有两个文件。
first.py
Class Repo:
def my_function:
variable = []
现在,我在另一个目录中有第二个文件,并且想要创建类似以下内容的文件:
second.py
def my_second_function(variable):
print(variable) # or some other operations on variable
如何使上面的代码起作用?我尝试过类似的东西:
import sys
sys.path.insert(1, 'path')
from first import *
但是它不起作用。你有什么想法吗?
虽然我对您的目标尚不完全清楚,但这是一种在一个文件中定义全局变量的方法,然后可以通过您尝试的sys.path方法将其导入:
test_dir/file1.py:
global_var1 = 'global_var1' # This variable is available upon import of file1.py
def fun():
global global_var2
global_var2 = 'global_var2' # This variable will be available after having called fun()
file2.py:
import sys
sys.path.insert(1, 'test_dir')
import file1
print(file1.global_var1)
#print(file1.global_var2) # This would fail
file1.fun()
print(file1.global_var2) # This works