【发布时间】:2021-06-22 16:12:28
【问题描述】:
我正在尝试将多个变量从一个文件导入另一个文件,而不是两次运行第一个文件。具体来说,我有一个名为“run_all_files.py”的脚本,它循环遍历本地目录中的文件以按顺序运行,这就是我要执行相关文件的脚本。在文件“file_1.py”中,我想将import变量A和B放入“file_2.py”,但我不想让“file_1.py”重新运行。
我也尝试调用if __name__=='__main__': 函数,但无法自行将变量A 和B 获取到import,并且“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'] 以实现所需的输出**
【问题讨论】:
-
变量
A和B是“file_1.py”中run_first_file()函数的本地——换句话说,它们不是模块级变量. -
martineau - 仍然可以将这些变量导入 file_2.py 吗?根据我的阅读,我仍然应该能够从 file_1.py 导入它们,但是您对这些变量是 file_1.py 的本地变量是正确的。还有办法调用“if__name__=='main' 或通过类导入变量吗?再次感谢!
-
我不相信有任何方法可以
import函数的局部变量。 -
您问题中的代码有几个与您所问的内容无关的拼写错误,并且无法运行。
-
如果您在“file_1.py”脚本中的
run_first_file()函数的开头声明变量global A, B,则可以import变量(在修复其他语法错误和印刷错误之后)您发布的代码)。这将防止它们成为局部变量。
标签: python variables import automation main