2010-08-17 40 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