Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在程序执行后导入程序的python变量_Python_Variables_Import_Main - Fatal编程技术网

在程序执行后导入程序的python变量

在程序执行后导入程序的python变量,python,variables,import,main,Python,Variables,Import,Main,我已经编写了两个python脚本script1.py和script2.py。我想从script2.py运行script1.py,并获取在script1执行过程中创建的script1变量的内容。Script1有几个创建变量的函数,包括main中的函数 谢谢你的回答。我检查了你的答案,但似乎不起作用。 以下是我所说的犯罪脚本: 脚本1.py def main(argv): """Main of script 1 Due to the internal structure of th

我已经编写了两个python脚本script1.py和script2.py。我想从script2.py运行script1.py,并获取在script1执行过程中创建的script1变量的内容。Script1有几个创建变量的函数,包括main中的函数

谢谢你的回答。我检查了你的答案,但似乎不起作用。 以下是我所说的犯罪脚本:

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

脚本2.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()
import script1

...
script1.dostuff()
importantvar = script1.importantvar
doScript2Stuff(importantvar)
为我的错误感到抱歉,谢谢你中肯的评论。我收到以下错误消息:

“AttributeError:'模块'对象没有属性'vroot\u 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()

根据要传递给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]
...

script2
do

import script1
这将运行
script1
中的任何代码;任何全局变量都将可用,例如
script1.计算结果
。您可以如下设置全局变量


脚本1:

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

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

请注意,最好在script1中使
main()
返回
result
,这样您就可以

import script1
result = script1.main( )

这更好地封装了数据流,并且通常更符合python。它还避免了全局变量,这通常是一件坏事。

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

然而,在不了解您的应用程序的情况下,我建议将script1所做的任何事情封装到一个函数中,这样您就可以简单地调用

(var1, var2, var3) = script1.dostuffAndReturnVariables()
因为避免全局变量总是好的。此外,如果在导入script1时没有执行script1中的内容(就像直接在主级别上编写所有命令一样),但在需要时,通过调用函数,它可能会变得很有用。否则,当您获得更多模块时,事情可能会变得一团糟,您可能会发现自己正在重新排列导入命令,因为它们做了很多事情

第二种可能性是,如果出于某种原因,它们需要单独运行,则使用pickle

在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:]) 
然后

inputfile = open(picklefile, "r")
vars = pickle.load(inputfile)
input.close()
在script2.py中。通过这种方式,您可以将var的内容保存在一个文件中,并在需要时从该文件中恢复它们


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

Python是一种解释性语言,因此当您只需在另一个脚本中导入脚本时(例如,在script2中编写
导入script1
)然后解释器将加载第二个脚本并逐步执行它。每个函数定义将产生一个可调用的函数对象,依此类推,并且每个表达式都将简单地执行


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

我认为您需要的是某种形式的对象持久性。我个人使用搁置模块来实现以下目的:

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

搁置模块在其实现中使用pickle模块,因此您也可以查看pickle模块以了解另一种方法。

-1您不应该使用命令行在Python模块之间进行通信。当然,这只是一个建议,也许这是他实现目标的唯一方法。好吧,但我想不出在什么情况下你会这么做<代码>pickle如果不能在运行时传递数据,那么它将是一种更好的方式。这种行为真的与python作为解释语言有关吗?(不是反问;)这个概念至少不适用于链接语言,因为在链接过程中只设置了一些引用,而没有执行任何语句。在这种语言中,您必须将所有内容都放在初始化函数中并手动调用它;在这里发布时,您应该使用良好的格式。错误是什么?您所编写的内容应该是有效的。如果这是
script2.py
的全部内容,那么它当然不起作用——您还没有包括
import script1
!正如我和其他一些人在下面所说的,从你的帖子中我得到的印象是,你想要运行script1,然后在将来的某个时候,你可以运行Script2,并且仍然可以获得script1中设置的值。是吗?是的,而且script1必须从script2运行。没有导入或命令(如os.system)可以执行此操作?谢谢!我将尝试这种方法。我已经尝试过,但不幸的是,它不起作用,出现以下消息:keyrerror:'vroot_directory'(如果我尝试像现在这样获取另一个变量,我会得到相同的消息)@Bruno-如果您得到一个键错误,有两种可能的解释。这两个程序是否从同一目录运行?如果检查调用文件的位置及其容器目录,是否找到mySettings文件?您可能需要在这两个脚本中提供shelve.open()的完整路径,以确保它们拾取相同的对象。感谢您提供的提示。我查看了mySettings文件,它位于正确的目录中。我把路径改为绝对路径,结果是一样的。为了启动这个程序,我在script2.py操作系统(“./script.py-d directory-t testcase_list_file”)(在script1.py上执行了chmod+x之后)中尝试过,结果在终端上得到了消息sh:script1.py:command not found。rgds,我的错误:再次尝试后,一切都很好!非常感谢gddc和所有人的时间和帮助。rgds,