【发布时间】:2011-03-30 21:08:09
【问题描述】:
我编写了两个 python 脚本 script1.py 和 script2.py。我想从 script2.py 运行 script1.py 并获取 script1 执行期间创建的 script1 变量的内容。 Script1 有几个函数可以在其中创建变量,包括在主函数中。
感谢您的所有回答。我已经检查了您的答案,但它似乎不起作用。 以下是我所说的有罪脚本:
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()
【问题讨论】:
-
我已经清理了你的代码;在这里发布时应该使用良好的格式。错误是什么?你写的应该可以工作。
-
如果那是
script2.py的全部 内容,那当然不行——你还没有包含import script1!正如我和其他几个人在下面所说的那样。 -
从您的帖子中,我得到的印象是您想要运行 script1,然后在未来的某个时间能够运行脚本 2 并且仍然获得在 script1 中设置的值。对吗?
-
是的,并且 script1 必须从 script2 运行。没有导入或命令(如 os.system)能够做到这一点?
标签: python variables import main