0

script1.py と script2.py という 2 つの Python スクリプトを作成しました。script2.py から script1.py を実行し、script1 の実行中に作成された script1 の変数の内容を取得したいと考えています。Script1 には、main を含め、変数が作成されるいくつかの関数があります。

ご回答ありがとうございます。私はあなたの答えを調べましたが、うまくいかないようです。ここに私が話している有罪のスクリプトがあります:

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' オブジェクトに属性 '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()
4

5 に答える 5

4

からscript2_

import script1

これにより、内部のコードが実行されscript1ます。グローバル変数は、たとえば として利用できますscript1.result_of_calculation。以下のようにグローバル変数を設定できます。


スクリプト 1:

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

スクリプト 2:

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

script1main() returnで作成する方が良いことに注意してresultください。

import script1
result = script1.main( )

これにより、データの流れがより適切にカプセル化され、一般的により Pythonic になります。また、一般的に悪いことであるグローバル変数を回避します。

于 2010-08-17T09:19:25.200 に答える
0

2 つの可能性があります。まず、それらを 1 つのスクリプトにマージします。これは次のようになります (script2.py 内)

import script1

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

ただし、アプリケーションを知らなくても、 script1 が行うことは何でも関数にカプセル化して、簡単に呼び出すことができるようにすることをお勧めします

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

グローバル変数を避けるのは常に良いことだからです。また、スクリプト 1 をインポートした瞬間にスクリプト 1 の内容が実行されない場合 (メイン レベルですべてのコマンドを直接記述した場合に実行されるため)、後で便利になる可能性がありますが、必要な場合は、機能。そうしないと、より多くのモジュールを取得すると、物事が乱雑になり、インポートコマンドが非常に多くのことを行うため、インポートコマンドを再配置することに気付く場合があります.

2 つ目の可能性として、何らかの理由でそれらを個別に実行する必要がある場合は、pickle を使用することです。

書く

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 の内容をファイルに保存し、必要に応じてそこからそれらを復活させることができます。

ただし、コードの構造が改善されるため、2 つを一緒に実行しない正当な理由がない限り、最初のアプローチをお勧めします。

于 2010-08-17T09:22:26.217 に答える
0

Python はインタープリター言語であるため、スクリプトを別のスクリプト内にインポートすると (たとえば、import script1script2 内に記述することによって)、インタープリターは 2 番目のスクリプトを読み込み、それを段階的に実行します。各関数定義は呼び出し可能な関数オブジェクトなどになり、各式は単純に実行されます。

その後、モジュールからすべてにアクセスできますscript1.globalvar1

于 2010-08-17T09:22:35.560 に答える
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 モジュールを調べることもできます。

于 2010-08-17T15:18:11.047 に答える
-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]
...
于 2010-08-17T09:18:56.117 に答える