在python中多次从外部文件调用变量
我正在尝试从外部文件调用变量。为此我写了这段代码在python中多次从外部文件调用变量,python,python-3.x,python-import,python-module,Python,Python 3.x,Python Import,Python Module,我正在尝试从外部文件调用变量。为此我写了这段代码 count = 1 while (count <= 3): # I want to iterate this line # rand_gen is the python file # A is the varialbe in rand_gen.py # Having this expression A = np.random.randint(1, 100) from rand_gen import A
count = 1
while (count <= 3):
# I want to iterate this line
# rand_gen is the python file
# A is the varialbe in rand_gen.py
# Having this expression A = np.random.randint(1, 100)
from rand_gen import A
print('Random number is ' + str(A))
count = count + 1
如何从文件
rand_gen.py
调用变量A
,每次它进入循环时都使用更新的值?请提供帮助。如果将随机值指定给变量,则引用该变量不会使值发生更改,无论该值是如何获得的
a = np.random.randint(1, 100)
a # 12
# Wait a little
a # still 12
同样,当您导入模块时,执行模块代码,并为a
分配一个值。除非使用importlib.reload
重新加载模块,或者再次调用np.random.randint
,否则A
没有理由更改值
您可能想要的是使成为一个
函数,返回所需范围内的随机值
# In the rand_gen module
def A():
return np.random.randint(1, 100)
在python中,
import
不是这样工作的。导入后,模块
缓存在系统模块
中,作为键
,值
模块名称和模块对象对。当您再次尝试导入相同的模块
时,只需将已缓存的值取回来即可。但是sys.modules
是可写的,删除键将导致python
检查模块并再次加载
尽管Olivier的答案是正确的方法,但为了理解import
,您可以尝试以下方法:
import sys # Import sys module
count = 1
while (count <= 3):
# I want to iterate this line
# rand_gen is the python file
# A is the varialbe in rand_gen.py
# Having this expression A = np.random.randint(1, 100)
if 'rand_gen' in sys.modules: # Check if "rand_gen" is cached
sys.modules.pop('my_rand') # If yes, remove it
from my_rand import A # Import now
print('Random number is ' + str(A))
count = count + 1
建议您阅读官方Python文档,以便彻底理解。读取值A
不会更改该值,它是在您第一次加载模块时分配的。为什么不直接调用np.random.randint(1100)
。您可以强制它,但它非常不直观,例如,import-importlib;importlib.reload(rand_gen)
或者,使A
成为一个函数并调用它,例如def A():返回np.random.randint(1100)
然后str(A())
每次都会给你一个不同的值。谢谢@akshat这是我想要的。因为我的实际代码是不同的,这个方法适用于这一点。再次感谢。很高兴能帮上忙:)
import sys # Import sys module
count = 1
while (count <= 3):
# I want to iterate this line
# rand_gen is the python file
# A is the varialbe in rand_gen.py
# Having this expression A = np.random.randint(1, 100)
if 'rand_gen' in sys.modules: # Check if "rand_gen" is cached
sys.modules.pop('my_rand') # If yes, remove it
from my_rand import A # Import now
print('Random number is ' + str(A))
count = count + 1
Random number is 6754
Random number is 963
Random number is 8825