执行后导入Python程序的变量

0 投票
5 回答
532 浏览
提问于 2025-04-16 02:54

我写了两个Python脚本,分别是script1.py和script2.py。我想从script2.py中运行script1.py,并获取在执行script1时创建的变量内容。script1里有几个函数,这些函数中会创建变量,包括在主程序部分。

谢谢大家的回答。我看过你们的建议,但似乎都不太管用。以下是我提到的有问题的脚本:

script1.py

def main(argv):
    """Main of script 1
    Due to the  internal structure of the script this 
    main function must always be called with the flag -d
    and a corresponding argument.
    """
    global now
    now = datetime.datetime.now()

    global vroot_directory
    vroot_directory = commands.getoutput("pwd")

    global testcase_list_file
    testcase_list_file = 'no_argument'

    try:
        opts, args = getopt.getopt(argv, "d:t:", 
            ["directory_path=", "testcase_list="])
    except getopt.GetoptError, err:
        print command_syntax
        sys.exit()
    for opt, arg in opts:
        if opt in ("-d", "--directory"):
            vroot_directory = arg
        if opt in ("-t", "--testcase"):
             testcase_list_file = arg

    def function1():
        pass  

    def function2():
        if testcase_list_file == 'no_argument':
            function1()
        else:
            function2()

if __name__ == "__main__":
    main(sys.argv[1:]) 

script2.py

from Tkinter import *

class Application:
    def __init__(self):
        """ main window constructor """
        self.root = Tk()
        # I'd like to import here the variables of script1.py
        self.root.title(script1.vroot_directory)   ?
        self.root.mainloop()

# Main program
f = Application()

抱歉我犯了一些错误,也感谢你们的相关意见。我收到了以下错误信息:

“AttributeError: 'module' object has no attribute 'vroot_directory'”

更具体一点,我希望能得到类似下面的内容:

from Tkinter import *
import script1

class Application:
    def __init__(self):
        """ main window constructor """
        self.root = Tk()
        script1.main(-d directory -t testcase_list_file) # to launch script1
        self.root.title(script1.vroot_directory)   # and after use its variables and functions
        self.root.mainloop()

# Main program
f = Application()

5 个回答

0

这里有两种可能性:第一种是把它们合并成一个脚本。这个脚本可能看起来像这样(在script2.py中)

import script1

...
script1.dostuff()
importantvar = script1.importantvar
doScript2Stuff(importantvar)

不过,在不了解你的应用程序的情况下,我建议把script1做的事情封装成一个函数,这样你就可以简单地调用

(var1, var2, var3) = script1.dostuffAndReturnVariables()

因为尽量避免使用全局变量总是好的。此外,如果script1中的内容不是在你导入它的时候就执行(就像你把所有命令直接写在主层面时那样),而是你需要的时候通过调用一个函数来执行,这样在后面可能会很方便。否则,一旦你有了更多的模块,事情可能会变得混乱,你可能会发现自己需要重新安排导入命令,因为它们做了太多事情。

第二种可能性是,如果出于某种原因,它们需要单独运行,可以使用pickle。

在script1.py中写

output = open(picklefile, "w")
pickle.dump(vars, output)    
output.close()

然后在script2.py中写

inputfile = open(picklefile, "r")
vars = pickle.load(inputfile)
input.close()

这样,你就可以把变量的内容保存到一个文件中,并在需要的时候从那里恢复它们。

不过,我更倾向于第一种方法,除非有很好的理由让这两个脚本不能一起运行,因为这样可以改善你的代码结构。

4

script2 开始

import script1

这段代码会运行 script1 里的所有内容;在这里,任何全局变量都可以用,比如 script1.result_of_calculation。你可以像下面这样设置全局变量。


script1:

from time import sleep
def main( ):
    global result
    sleep( 1 ) # Big calculation here
    result = 3

script2:

import script1
script1.main( ) # ...
script1.result # 3

需要注意的是,如果让 script1 里的 main() 返回 result 会更好,这样你就可以这样做

import script1
result = script1.main( )

这样做可以更好地管理数据流动,而且通常来说更符合 Python 的编程风格。同时,这样也避免了使用全局变量,而全局变量通常是不太好的做法。

0

我觉得你想要的其实是某种对象的持久化,也就是让你的数据能够保存下来,不会在程序关闭后消失。我个人是用shelve模块来实现这个功能的:

脚本1:

import shelve

def main(argv):
    """Main of script 1
    Due to the  internal structure of the script this 
    main function must always be called with the flag -d
    and a corresponding argument.
    """

    settings = shelve.open('mySettings')

    global now
    now = datetime.datetime.now()

    settings['vroot_directory'] = commands.getoutput("pwd")

    settings['testcase_list_file'] = 'no_argument'

    try:
        opts, args = getopt.getopt(argv, "d:t:", 
            ["directory_path=", "testcase_list="])
    except getopt.GetoptError, err:
        print command_syntax
        sys.exit()
    for opt, arg in opts:
        if opt in ("-d", "--directory"):
            settings['vroot_directory'] = arg
        if opt in ("-t", "--testcase"):
            settings['testcase_list_file'] = arg

    def function1():
        pass  

    def function2():
        if testcase_list_file == 'no_argument':
            function1()
        else:
            function2()

if __name__ == "__main__":
    main(sys.argv[1:]) 

脚本2:

from Tkinter import *
import shelve

class Application:
    def __init__(self):
        settings = shelve.open('mySettings')

        """ main window constructor """
        self.root = Tk()
        # I'd like to import here the variables of script1.py
        self.root.title(settings['vroot_directory'])   ?
        self.root.mainloop()

# Main program
f = Application()

shelve模块在实现过程中使用了pickle模块,所以你也可以看看pickle模块,作为另一种方法。

撰写回答