在python中保存变量的值

时间:2017-02-21 18:36:58

标签: python

是否可以保存某些变量的值,然后在另一个模块中的另一个函数中使用它? 例如

#file1.py

def function1():
    a = raw_input("Type: ")
    return a

#file2.py
import file1

def function2():
    x = file1.function1()
    if x == '5':
        print "True"
    else:
        print "False"

这个file1.py是我程序的一部分,后来在另一个模块中,我想使用之前输入的特定值' a'但不是那样它打印我"键入:"反复 而且因为我需要多次这个价值,所以我不想要它输入值然后继续编程。 实际上,我想输入一次值然后记住它并稍后通过调用特定函数多次使用它。

1 个答案:

答案 0 :(得分:0)

我的建议是使用搁置模块并保存变量。这可以在file2.py中打开,就像我在下面的代码中打开它一样:

import shelve

def save_variable(save):
    file = shelve.open('variable_a' , 'n')
    file['a'] = save
    file.close()

def load_variable():
    file = shelve.open('variable_a' , 'r')
    load = file['a']
    file.close()
    return load

def function1():
    try: a = load_variable() #Try load the variable from file
    except: #Doesnt exist - so we create it here
        a = raw_input('Enter the var here: ' )
        save_variable(a)
    return a

print function1()