[英]How to pass a variable from one Python script to another?
我知道这个问题已经在我已经阅读过很多的论坛广告中进行了讨论,但是我仍然没有所需的解决方案。
以下代码是我的真实代码的非常简化的版本。
我的第一个脚本如下(kyssa1.py):
import os
import sys
def type():
global dictionary
dictionary="C:\Python27\Myprojects\physics.txt"
os.system("C:\Python27\Myprojects\kyssa2.py")
from Tkinter import *
t = Tk()
b = Button(t, text="Start", command = lambda:type())
b.pack(expand=Y)
t.mainloop()
我的第二个脚本(kyssa2.py)如下:
# -*- coding: utf-8 -*-
from kyssa1 import dictionary
def open():
global dictionary
global lines
global datafile
datafile = file(dictionary)
lines = [line.decode('utf-8').strip() for line in datafile.readlines()]
for i in lines:
text.insert(END, i)
open()
from Tkinter import *
root = Tk()
text = Text(root,font=("Purisa",12))
text.pack()
root.mainloop()
我想做的是在kyssa2.py中打开文件physics.txt,并使用此文本在函数open()中执行命令,但这并不符合我的意愿。 单击“开始”按钮会出现另一个窗口,就像在“ kyssa1.py”中定义的那样。 如何将变量字典从一个脚本传递到另一个脚本?
在kyssa1.py
在模块范围内声明dictionary
,即在type()
函数之外。 您不需要在kyssa2.py
使用global
,您可以直接引用dictionary
。
另外,要打开文件,请使用open()
而不是file()
:
datafile = open(dictionary)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.