繁体   English   中英

在导入文件“ b”中,如何使用从文件“ a”读取到主文件“ c”中的变量?

[英]how to use variables read from file “a” into the main file “c”, in a imported file “b”?

我有一个文件,例如“ c.py”和一个导入的文件“ b.py”,稍后在代码中的“ c.py”中将其使用

import b.py
def scatter_plot(file0,camp):

    # enter complete path of file
    file1 = ("/home/data/camp0" + str(camp) + "/not_detrended/ktwo"+ str(file0)+ "c0"+ str(camp)+ "_lpd_LC.txt")
    file2 = file1.replace("not_","")
    file3 = open('/home/parameters1.txt','r')

    y = np.genfromtxt(file1)
    x = np.genfromtxt(file2)
    text = file3.read()
    specs = text.split()

    #Input the parameters
    i = specs.index(str(file0))
    t0 = float(specs[i + 2])
    period = float(specs[i + 1])
    .......

在主文件c.py中,我读取了文本文件“ file3”并获取了上面的变量(t0和period)。 我已经导入了一个文件“ b.py”,该文件也使用了这些变量,但是为了获得代码工作,我必须在运行c.py之前在文件b.py中定义和修复这些变量,我不能从“ file3。我想通过调用函数scatter_plot()运行主文件“ c.py”,并希望变量也由此从导入文件“ b.py”中定义。当我调用函数时,我想在导入的文件中也使用这些变量,这可能吗?

par = [tduration, depth, t0, period]    
firstmodel = traptransitover.traptransitover( time, par)
newmodel  = traptransitover.traptransitover( time, result)

上面的代码是“ b.py”的几行。 如果我没有在“ b.py”中定义变量t0和句点,并在运行“ c.py”之前对其进行修复,那么它将无法正常工作。 但是,如果这样做,就没有使用从“ file3”中读取变量的功能。 在运行代码之前,我无法每次都定义。 抱歉,如果我无法解释我的问题,并且您需要进一步说明,请告诉我。 谢谢。

如果我了解你的权利

  1. 您需要在3个模块之间共享一些变量。
  2. 要初始化此变量,您需要读取文件
  3. 程序启动时文件未定义(即,您需要解析参数或读取用户输入)

最好的方法是重写模块a.py,b.py和c.py,因此thay将能够在不知道此变量的情况下导入。 所有使用变量的代码必须包装到接受参数(t0和句点)作为参数的函数或类中,并且在“ c.py”不解析文件之前,不应调用它们。

另一种方法是创建另一个模块(例如“ config.py”)来存储变量,并将该模块包括在所有其他模块中。在用文件初始化config之前,您将无法导入其他模块。

config.py

t0 = None
period = None
def initialize_t_and_period( file ):
     global t0
     global period

     #here code for initialization t0 and period  from scatter_plot

模块b.py

import config
do_something_with( config.t0 )
...

模块c.py

import config

def scatter_plot( file0, camp ):
    config.initialize_t_and_period( file0 )

    #after initialization you can safety import modules       
    import a
    import b

如果文件始终相同(即预定义),则可以在config.py中读取它。 尽管config在程序运行期间导入了两次,但它只会执行一次。

暂无
暂无

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

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