从 Python 文件调用函数

Calling a func from a Python file

我有两个 Python 文件(使用 PyCharm)。在 Python 文件#2 中,我想调用 Python 文件#1 中的函数。

from main import load_data_from_file

delay, wavelength, measured_trace = load_data_from_file("Sweep_0.txt")
print(delay.shape)

哪个主要是 python 文件#1 的名称。但是,当我 运行 python file#2(代码发布在顶部)时,我可以看到整个 python file#1 也是 运行ning。 关于如何 运行 print(delay.shape) 而无需 运行 整个 python file#1 的任何建议??

这是我的代码:

class import_trace:
def __init__(self,delays,wavelengths,spectra):
    self.delays = delays
    self.wavelengths = wavelengths
    self.spectra = spectra

def load_data_from_file(self, filename):

    # logging.info("Entered load_data_from_file")
    with open(filename, 'r') as data_file:
        wavelengths = []
        spectra = []
        delays = []
        for num, line in enumerate(data_file):
            if num == 0:
                # Get the 1st line, drop the 1st element, and convert it
                # to a float array.
                delays = np.array([float(stri) for stri in line.split()[1:]])
            else:
                data = [float(stri) for stri in line.split()]
                # The first column contains wavelengths.
                wavelengths.append(data[0])
                # All other columns contain intensity at that wavelength
                # vs time.
                spectra.append(np.array(data[1:]))
    logging.info("Data loaded from file has sizes (%dx%d)" % 
    (delays.size, len(wavelengths)))
    return delays, np.array(wavelengths), np.vstack(spectra)

及以下我使用它来获取值,但是它不起作用:

frog = import_trace(delays,wavelengths,spectra)
delay, wavelength, measured_trace = 
frog.load_data_from_file("Sweep_0.txt")

我收到这个错误:

frog = import_trace(delays,wavelengths,spectra)
NameError: name 'delays' is not defined

您可以将文件 1 的函数包装在 class 中,而在文件 2 中您可以创建对象并调用特定函数。但是,如果您可以共享文件 1 的代码,那就很清楚了。以下内容供您参考...

文件-1

class A:
    def func1():
        ...

文件-2[=​​20=]

import file1 as f
# function call
f.A.func1()