简体   繁体   English

执行后导入程序的python变量

[英]Importing python variables of a program after its execution

I've written two python scripts script1.py and script2.py. 我已经编写了两个python脚本script1.py和script2.py。 I want to run script1.py from script2.py and get the content of the variables of script1 created during the execution of script1. 我想从script2.py运行script1.py并获取执行script1期间创建的script1变量的内容。 Script1 has several functions in which the variables are created including in the main. Script1具有几个函数,可在其中创建变量,包括在main中。

Thank you for all your answers. 感谢您的所有答复。 I've examined your answers and it doesn't seem to work. 我已经检查了您的答案,但似乎没有用。 Here are the guilty scripts I'm talking about : 这是我正在谈论的有罪脚本:

script1.py 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 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()

Sorry for my mistakes and thank you for your pertinent remarks. 对不起,我的错,也谢谢您的相关评论。 I've got the following error message : 我收到以下错误消息:

" AttributeError: 'module' object has no attribute 'vroot_directory' " “ AttributeError:'模块'对象没有属性'vroot_directory'”

To be more specific I'd like to have something similar to the following : 更具体地说,我想拥有类似以下内容:

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()

From script2 do script2

import script1

This will run any code inside script1 ; 这将在script1内运行任何代码; any global variables will be available as eg script1.result_of_calculation . 任何全局变量都将可用,例如script1.result_of_calculation You can set global variables as below. 您可以如下设置全局变量。


script1: SCRIPT1:

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

script2: SCRIPT2:

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

Note that it would be nicer to make main() in script1 return result , so that you could do 请注意,这将是更好的main()在SCRIPT1返回result ,这样就可以做

import script1
result = script1.main( )

This better encapsulates the flow of data, and is generally more Pythonic. 这样可以更好地封装数据流,并且通常使用Python语言。 It also avoids global variables, which are generally a Bad Thing. 它还避免了通常是不好的事情的全局变量。

There are two possibilities: First, merge them into a single script. 有两种可能性:首先,将它们合并为一个脚本。 This could look something like (in script2.py) 可能看起来像(在script2.py中)

import script1

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

Without knowing your application, however, I'd advise encapsulating whatever script1 does into a function such that you can simply call 但是,不知您的应用程序,我建议将script1所做的任何事情封装到一个函数中,以便您可以简单地调用

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

since it's always good to avoid global variables. 因为避免全局变量总是好事。 Also, it may turn out handy later on if the stuff in script1 isn't executed in the moment you import it (as it is done if you write all the commands directly on the main level), but when you want it, by calling a function. 另外,如果在导入脚本1时没有执行脚本1中的内容(例如,如果直接在主级别上直接编写所有命令,则可以完成该操作),则稍后可能会派上用场,但是如果需要,可以通过调用一个功能。 Otherwise things may get messy once you get more modules and you may find yourself rearranging import commands because they do so much stuff. 否则,一旦获得更多模块,事情可能会变得混乱,您可能会发现自己重新排列了导入命令,因为它们会做很多事情。

Second possibility, if, for some reason, they need to be run separately, would be to use pickle. 如果由于某种原因需要单独运行它们,第二种可能性是使用泡菜。

Write

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

in script1.py 在script1.py中

and then 接着

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

in script2.py. 在script2.py中。 This way, you save the contents of your var in a file and can revive them from there when needed. 这样,您可以将var的内容保存在文件中,并可以在需要时从那里恢复它们。

However, I'd prefer the first approach unless there's a really good reason for the two not to be run together, as it improves the structure of your code. 但是,我宁愿采用第一种方法,除非有充分的理由使两者不一起运行,因为这会改善代码的结构。

Python is an interpreted language, so when you simply import a script within another script (eg by writing import script1 inside script2) then the interpreter will load the second script and execute it step by step. Python是一种解释型语言,因此当您简单地在另一个脚本中导入一个脚本(例如,通过在script2内编写import script1脚本1)时,解释器将加载第二个脚本并逐步执行它。 Each function definition will result in a callable function object and so on, and each expression will be simply executed. 每个函数定义将导致可调用的函数对象,依此类推,并且每个表达式都将被简单执行。

After that, you can access everything from the module with script1.globalvar1 and so on. 之后,您可以使用script1.globalvar1等访问模块中的所有内容。

I think what you are looking for is some form of object persistence. 我认为您正在寻找的是某种形式的对象持久性。 I personally use the shelve module for this: 我个人为此使用了搁置模块:

Script 1: 脚本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:]) 

Script 2: 脚本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()

The shelve module uses the pickle module in its implementation, so you could also look at pickle module for another approach. 货架模块在其实现中使用了pickle模块,因此您也可以查看pickle模块的另一种方法。

Depending on how many variables you want to pass to script2.py you could pass them via arguments and pick them up as an argv array. 根据要传递给script2.py的变量的多少,可以通过参数传递它们并将其作为argv数组。 You could run script1.py then from this script run os.system('script2.py arg0 arg1 arg2 arg3') to call script2.py. 您可以运行script1.py,然后从此脚本运行os.system('script2.py arg0 arg1 arg2 arg3')来调用script2.py。

Then you can pick up your variables in you script2.py by doing this: 然后,您可以通过执行以下操作在script2.py中获取变量:

import sys

arg0 = sys.argv[0]
arg1 = sys.argv[1]
...

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

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