将变量从一个文件导入另一个文件

问题描述

我试图将多个变量从一个文件导入到另一个文件中,而没有运行第一个文件两次。具体来说,我有一个名为“run_all_files.py”的脚本,它循环遍历本地目录中的文件以按顺序运行,这是我想要执行相关文件的脚本。在文件“file_1.py”中,我想将 import 变量 AB 放入“file_2.py”但我不希望“file_1.py”重新运行.

我也尝试调用 if __name__=='__main__': 函数,但无法自行获取变量 ABimport,并且“file_1.py”仍然运行两次。 “file_1.py”和“file_2.py”都位于列出的path中,并在运行“run_all_files.py”时执行。

"run_all_files.py"

import os
path = "C:\\users\\mdl518\\Desktop\\"
def run_the_files():

    file_list = ['file_1.py','file_2.py']
    for filename in file_list:
        os.system('python' + ' ' + os.path.join(path,filename))

run_the_files()

“file_1.py”

import os
def run_first_file():

    global A,B
    A = 'Hello'
    B = 'User'
    C = 'Python Programmer'
    print("This is the first file to run")

run_first_file()

“file_2.py”

import os
from file_1 import A,B

def run_second_file():

    print('Welcome,and ',A + ' ' + B) 
    print("This second program runs smoothly")

run_second_file()

当前输出

This is the first file to run
This is the first file to run
Welcome,and  Hello User
This second program runs smoothly

所需的输出

This is the first file to run
Welcome,and  Hello User
This second program runs smoothly

** 更新:将 "run_all_files.py" 中的 file_list 更改为 file_list = ['file_2.py'] 以实现所需的输出 **

解决方法

一种可能性是,如果你去上课,绝对不优雅,但有效。

“file_1.py”

With ActiveSheet
    Range(.Rows(8),.Rows(.Rows.Count)).Columns("C:J").ClearContents
End With

“file_2.py”

from var import sol
class v(object):
    sol = 'Hello'