2010-08-17 4 views
0

나는 두 개의 python 스크립트 script1.py와 script2.py를 작성했습니다. script2.py에서 script1.py를 실행하고 script1을 실행하는 동안 생성 된 script1의 변수 내용을 가져 오려고합니다. Script1에는 주 변수를 포함하여 변수가 생성되는 몇 가지 함수가 있습니다.실행 후 프로그램의 파이썬 변수 가져 오기

답장을 보내 주셔서 감사합니다. 나는 당신의 대답을 조사했으나 효과가없는 것 같습니다. 다음은 제가 이야기 유죄 스크립트입니다 :

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

죄송합니다

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하고 관련 발언에 감사드립니다 . 나는 다음과 같은 오류 메시지가 있어요 :

"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

+0

이것이'script2.py'의 * 전체 내용이라면, 그것은 효과가 없을 것입니다 - 당신은'import script1'을 포함하지 않았습니다! 나와 다른 몇몇 사람들이 아래에서 말했듯이. – katrielalex

+0

귀하의 게시물에서 나는 당신이 script1을 실행하고자하는 인상을 받았고, 얼마 후에는 script2를 실행하고 여전히 script1에 설정된 값을 얻을 수 있어야합니다. 그 맞습니까? –

답변

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

+0

시도했지만 불행히도 작동하지 않습니다. keyError : 'vroot_directory' (지금 다른 변수를 얻으려고하면 같은 메시지가 나타납니다) – Bruno

+0

@Bruno - If 몇 가지 가능한 설명이 있습니다. 두 프로그램이 같은 디렉토리에서 실행됩니까? 어디에서 파일을 호출했는지 확인하고 컨테이너 디렉토리에서 mySettings 파일을 찾으십니까? 두 스크립트에서 shelve.open()에 대한 전체 경로를 제공하여 동일한 객체를 선택해야 할 수도 있습니다. –

-2

script2.py에 전달할 변수의 수에 따라 인수를 통해 전달하고 argv 배열로 가져올 수 있습니다. 이 스크립트에서 script1.py를 실행하면 os.system ('script2.py arg0 arg1 arg2 arg3')을 실행하여 script2.py를 호출 할 수 있습니다. 이 작업을 수행하여 script2.py에

그런 다음 당신은 당신의 변수를 선택할 수 있습니다 : script2에서

import sys 

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

-1 명령 줄을 사용하여 파이썬 모듈간에 통신해서는 안됩니다. – katrielalex

+0

물론 이것은 단지 제안 일 뿐이며, 아마도 그의 상황에서 그가 자신의 목표를 달성 할 수있는 유일한 방법 인 것으로 드러났을 것입니다. – Martin

+0

글쎄, 알았어.하지만 네가해야 할 일은 생각할 수가 없어. 'pickle'은 런타임에 데이터를 전달할 수 없다면 데이터를 전달하는 더 좋은 방법입니다. – katrielalex

4

import script1 

이것은 script1 내부의 코드를 실행한다; 모든 전역 변수는 예를 들어 다음과 같이 사용할 수 있습니다. script1.result_of_calculation. 전역 변수는 다음과 같이 설정할 수 있습니다.


script1이 :

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

script2 : script1이이 result을 반환 당신이

을 할 수 있도록

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

참고가 될 것이라고 더 좋은main()를 만들기 위해

import script1 
result = script1.main() 

이 기능은 데이터 흐름을 캡슐화하며 일반적으로 더 Pythonic입니다. 또한 일반적으로 나쁜 것 인 전역 변수를 피합니다.

0

두 가지 가능성이 있습니다. 첫째, 단일 스크립트로 병합하십시오. 이것은 (script2에서와 같이) 보일 수 있습니다.평) 응용 프로그램을 모른 채

import script1 

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

그러나, 나는 그것이 전역 변수를 피하기 위해 항상 좋은 때문에 단순히

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

를 호출 할 수 있도록하는 기능으로 수행 어떤 script1이 캡슐화 좋을 걸. 또한, script1의 내용이 가져 오는 순간 실행되지 않으면 (나중에 주 레벨에서 모든 명령을 직접 작성하는 경우처럼), 나중에 필요할 때 스크립트를 호출하여 편리하게 사용할 수 있습니다. 함수. 그렇지 않으면 더 많은 모듈을 얻고 나면 물건이 엉망이 될 수 있습니다. 그리고 많은 것들을하기 때문에 가져 오기 명령을 다시 정렬 할 수 있습니다.

두 번째 가능성은 따로 달리기 위해 피클을 사용해야하는 경우입니다.

쓰기 script1.py

에서

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

및 script2.py에서 다음

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

. 이렇게하면 var의 내용을 파일에 저장하고 필요할 때 바꿀 수 있습니다.

그러나 두 코드가 함께 실행되지 않는 것이 좋은 이유가 아니라면 첫 번째 방법을 선호합니다. 코드의 구조가 개선되기 때문입니다.

0

파이썬은 해석 된 언어이므로 다른 스크립트에서 스크립트를 가져 오면 (예 : 을 스크립트 2에 작성하면) 인터프리터는 두 번째 스크립트를로드하고 단계별로 실행합니다. 각 함수 정의는 호출 할 수있는 함수 객체 등을 생성 할 것이고 각 표현식은 간단히 실행될 것입니다.

그런 다음 script1.globalvar1 등의 모듈에서 모든 항목에 액세스 할 수 있습니다.

+0

이 동작은 실제로 파이썬이 해석 된 언어와 관련이 있습니까? (수사학적인 질문이 아닙니다) – Nicolas78

+0

이 개념은 링크 된 언어로는 적어도 작동하지 않습니다. 왜냐하면 링크 과정 중에 일부 참조 만 설정되었지만 어떤 명령문도 실행되지 않았기 때문입니다. 그러한 언어에서는 모든 것을 초기화 함수에 넣고 수동으로 호출해야합니다. – tux21b