【问题标题】:Calling variable from external file multiple times in python在python中多次从外部文件调用变量
【发布时间】:2018-11-07 14:50:07
【问题描述】:

我正在尝试从外部文件调用变量。为此,我编写了这段代码,

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

但是当我运行我的代码时,它只调用一次变量A 并打印相同的结果。查看代码的输出,

Random number is 48
Random number is 48
Random number is 48

每次进入循环时,如何从文件rand_gen.py 调用具有更新值的变量A?请帮忙。

【问题讨论】:

  • 读取值A 不会更改值,它是在您第一次加载模块时分配的。你为什么不直接打电话给np.random.randint(1, 100)。您可以强制它,但它非常不直观,例如import importlib; importlib.reload(rand_gen)
  • 或者,将A 设为一个函数并调用它,例如def A(): return np.random.randint(1, 100) 然后str(A()) 每次都会给你一个不同的值。

标签: python python-3.x python-import python-module


【解决方案1】:

如果您为变量分配随机值,则无论该值是如何获得的,引用该变量都不会改变该值。

a = np.random.randint(1, 100)

a # 12
# Wait a little
a # still 12

同样,当你导入你的模块时,模块代码被执行并且一个值被分配给A。除非使用importlib.reload 重新加载模块或者您再次调用np.random.randint,否则A 没有理由更改值。

您可能想要使A 成为一个返回所需范围内的随机值的函数。

# In the rand_gen module
def A():
    return np.random.randint(1, 100)

【讨论】:

    【解决方案2】:

    这不是import 在 python 中的工作方式。导入后,modulekeyvalue 一对模块名称和模块对象缓存在 sys.modules 中。当您尝试再次导入相同的module 时,您只需取回已经缓存的值。但是sys.modules 是可写的,删除the 键会导致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
    

    输出

    Random number is 6754
    Random number is 963
    Random number is 8825
    

    建议阅读The import systemThe module cache 上的官方 Python 文档,以便深入了解。

    【讨论】:

    • 谢谢@akshat 这就是我想要的。因为我的实际代码不同,而这种方法适用于此。再次感谢您。
    • 很高兴能帮上忙 :)
    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多