2010-08-17 41 views
0

我写过两个python脚本script1.py和script2.py。我想从script2.py运行script1.py,并获取执行script1期间创建的script1的变量的内容。 Script1有几个功能,其中包括主要的变量。执行程序后导入python变量

谢谢你的答案。我已经检查了你的答案,但似乎并不奏效。 这里是我说的是有罪的脚本:

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的:‘模块’对象有没有属性‘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() 
+0

我清理了你的代码;在这里发布时,您应该使用良好的格式。什么是错误?你写的东西应该可以工作。 – katrielalex 2010-08-17 13:02:50

+0

如果这是'script2.py'的*全部*内容,它当然不起作用 - 你还没有包含'import script1'!正如我和其他几位人士所说的。 – katrielalex 2010-08-17 13:03:31

+0

从你的文章中我得到的印象是你想运行script1,然后在将来有一段时间能够运行脚本二,仍然可以获取在script1中设置的值。那是对的吗? – 2010-08-17 15:20:42

回答

0

我认为你正在寻找的是某种形式的对象持久性。我个人使用这个货架模块:

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

的货架模块使用咸菜模块中的执行,所以你也可以看看腌菜模块的另一种方法。

+0

谢谢!我会尝试这种方法。 – Bruno 2010-08-17 18:02:42

+0

我试过了,但不幸的是它不起作用, 出现以下消息: keyError:'vroot_directory' (如果我尝试获取像现在这样的其他变量,我得到了相同的消息) – Bruno 2010-08-17 20:46:06

+0

@Bruno - If你会得到一个关键的错误,有几个可能的解释。这两个程序是从同一个目录运行吗?如果你检查你从哪里调用文件和他们的容器目录,你会发现一个mySettings文件?您可能需要在两个脚本中提供shelve.open()的完整路径,以确保它们选取相同的对象。 – 2010-08-17 21:02:13

-2

取决于你想传递给script2.py的变量有多少,你可以通过参数传递它们并将它们作为argv数组。你可以运行script1.py然后从这个脚本运行os.system('script2.py arg0 arg1 arg2 arg3')来调用script2.py。

然后你就可以在你script2.py通过这样拿起您的变量:

import sys 

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

-1您不应该在Python模块与命令行之间进行通信。 – katrielalex 2010-08-17 09:19:56

+0

当然,这只是一个建议,也许这是他能够实现目标的唯一途径。 – Martin 2010-08-17 09:28:02

+0

好吧,好的,但我不能想到任何情况下你必须这样做。如果你不能在运行时执行,'pickle'会是传递数据的更好方式。 – katrielalex 2010-08-17 09:57:13

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 

注意,这将是更好使main()在SCRIPT1返回result,这样你就可以做

import script1 
result = script1.main() 

这更好地封装了数据流,而且通常是更多的Pythonic。它也避免了全局变量,这通常是一件坏事。

0

有两种可能:首先,将它们合并成一个脚本。这可能看起来像(在script2中)。PY)

import script1 

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

不知道你的应用程序,但是,我建议任何封装SCRIPT1做成一个函数,这样你可以简单地调用

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

,因为它总是很好的避免全局变量。另外,如果脚本1中的内容在导入时没有执行(如果直接在主级上写入所有命令时完成),则可能会变得非常方便,但是当您需要时,通过调用一个函数。否则,一旦获得更多模块,事情可能会变得混乱,并且您可能会发现自己重新整理了导入命令,因为它们做了很多事情。

第二种可能性,如果由于某种原因需要单独运行,则可以使用泡菜。

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

在script1.py

然后

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

。这样,您可以将var的内容保存在一个文件中,并可以在需要时从那里恢复它们。

但是,我更喜欢第一种方法,除非有一个非常好的理由让它们不能一起运行,因为它改进了代码的结构。

0

Python是一种解释型语言,所以当您只需在另一个脚本中导入脚本时(例如,通过在脚本2中编写import script1),解释器将加载第二个脚本并逐步执行。每个函数定义将产生一个可调用的函数对象等,并且每个表达式将被简单地执行。

之后,您可以使用script1.globalvar1等访问模块中的所有内容。

+0

这个行为是否真的与Python是一种解释型语言有关? (不是一个修辞问题;) – Nicolas78 2010-08-17 09:31:56

+0

这个概念至少不能用于链接语言,因为在链接过程中只有一些引用被设置,但是没有语句被执行。在这样的语言中,你必须把所有内容都放在一个初始化函数中,然后手动调用它。 – tux21b 2010-08-17 09:40:18