python - 将变量从一个 python 文件传递到另一个
问题描述
我有 3 个 py 文件;1 是从其他 2 个 py 文件运行功能的主文件。其他 2 个文件将从 excel 文件中获取数据。我将需要用户输入来确定是否从 excel 中收集哪组数据。在我的文件 1(主)的开头,我会要求用户输入 1 或 2,并将这个值存储到预定义的变量“模式”中。
'底部的更新代码'
但上面会告诉我关于模式未定义的错误。
我在网上找到了一些答案,我将模式输入放在文件 2 上,并在文件 1 和 3 上导入文件 2。它正在工作,但我不知道为什么它必须是一个函数,以及什么是“全局” ' 在这里做。有没有更好的方法将变量传递给其他文件?
有效的代码:
文件 1:
import file 2
import file 3
if file2.mode == '1':
function2 from file2
function3 from file3
elif file2.mode == '2':
function2 from file2
function3 from file3
文件 2:
def function():
global mode
mode = input(print("=>Input '1' for Eyebrow2D\n=>Input '2' for Eyebrow3D"))
function()
workfunction2():
文件 3:
if file2.mode == '1':
do something
elif file2.mode == '2':
do other thing
workfunction3():
编辑更新一些会让我出错的代码
文件 1:
from file2 import *
mode = input(print("=>Input '1' for option1\n=>Input '2' for option2"))
if mode == '1':
get_excel_data()
print(shape)
elif mode == '2':
get_excel_data()
print(shape)
文件 2
from file1 import *
###I will get error here for mode not define
if mode == '1':
data_xls = pd.read_excel('data.xlsx', sheet_name=2d)
data_xls.to_csv('data.csv', encoding='utf-8')
df = pd.read_csv(data.csv', header = 1, encoding = encoding)
elif mode == '2':
data_xls = pd.read_excel('data.xlsx', sheet_name=3d)
data_xls.to_csv('data2.csv', encoding='utf-8')
df = pd.read_csv(data2.csv', header = 1, encoding = encoding)
shape = []
def get_excel_data():
if mode == '1':
for value in df["Shape"]:
if type(value) == float:
if math.isnan(value):
print("empty")
continue
else:
str(value).strip()
excel_list.append(value)
else:
pass
也许我需要在文件 2 中使用 file1.mode?
解决方案
你不应该像你提到的那样这样做。
您必须以类似以下示例的方式执行此操作:
import file1
question = input(int("how old are you?"))
if question > 18:
file1.adult(question)
else:
file1.children(question)
推荐阅读
- laravel - 尝试安装 gloudemans/shoppingcart,安装失败,将 ./composer.json 还原为其原始内容?
- perl - 安装 perl 包时 ld 未知选项 -platform_version
- python - PyTorch 的“ToPILImage”问题
- r - 如何在 R 中使用 Ibrokers 一次交易多个股票
- php - 每次附加 file_put_contents 后,Filesize 无法获取实际文件大小
- csv - 处理大文件时出现 Awk 4.1.4 错误
- php - 如何在另一个 php 脚本的后台运行 php 脚本?
- macos - MAC OS 项目从 Fabric 升级到 FirebaseCrashlytics(没有 CoCOPod)
- unicode - 浏览器无法识别 UTF8
- c - 我的 C 程序陷入无限循环