我写了两个 python 脚本 script1.py 和 script2.py。我想从 script2.py 运行 script1.py 并获取 script1 执行期间创建的 script1 变量的内容。Script1 有几个函数在其中创建变量,包括在主函数中。
感谢您的所有回答。我已经检查了您的答案,但它似乎不起作用。这是我正在谈论的有罪脚本:
脚本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()
对我的错误感到抱歉,并感谢您的中肯评论。我收到以下错误消息:
“ 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()