繁体   English   中英

将变量从一个 python 文件传递到另一个

[英]Pass a variable from one python file to another

我有 3 个 py 文件; 1 是从其他 2 个 py 文件运行 function 的主文件。 其他 2 个文件将从 excel 文件中获取数据。 我需要用户输入来确定是否从 excel 收集哪组数据。 在我的文件 1(主)的开头,我会要求用户输入 1 或 2,并将这个值存储到预定义的变量“模式”中。

'底部的更新代码'

但上面会告诉我关于模式未定义的错误。

我在网上找到了一些答案,我将模式输入放在文件 2 上,并在文件 1 和 3 上导入文件 2。它正在工作,但我不知道为什么它必须是 function,以及什么是“全局” ' 在这里做。 有没有更好的方法将变量传递给其他文件?

有效的代码:

文件 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)

不需要任何全局变量,您只需定义函数并将数据传递为 arguments。 比如main应该是这样的

mode = input("1 or 2?")
if mode == '1':
     function_from_file2(mode)
     function_from_file3(mode)
elif mode == '2':
     do_something(mode)

在其他文件中

# file 2

def function_from_file2(mode):
    // add your functionally here 

其他文件也是如此

暂无
暂无

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

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