将变量传递给另一个Python脚本

2024-09-21 01:14:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难在另一个python脚本中将变量从一个函数传递到另一个函数。我读过其他的答案,但它们对这个问题没有真正的帮助。在

这是我想将变量发送到的第一个文件(为清晰起见,省略了一些代码)

# TestGUI.py

from Tkinter import *
import serial
import os

class Testgui:
    def __init__(self, master):

    def writetoBOT(self,instruct):
       ser = serial.Serial(6)
       ser.baudrate = 9600
       ser.parity = serial.PARITY_NONE #set parity check: no parity
       ser.timeout = 1            #non-block read
       ser.writeTimeout = 2     #timeout for writ

       if(ser.isOpen() == False):
           ser.open()
           print ser.portstr       # check which port was really used
           ser.write(instruct)
       else :
           ser.write(instruct)

这是第二个文件:

^{pr2}$

TypeError:调用未绑定方法writeBot()时,必须将TestGUI实例作为第一个参数(改为get str instance)


Tags: 文件函数importself脚本defchecktimeout
3条回答

或者,您可以为这两个脚本留出公共空间,it acn by database-sqllite

例如

# file1.py
import sqlite3

con = sqlite3.connect('messages.db')
cur = con.cursor()
#cur.execute('CREATE TABLE message (id INTEGER PRIMARY KEY, name TEXT, content TEXT, read INTEGER)')
#con.commit()


for x in range(100000):
    if x in range(1, 500): 
        cur.execute('INSERT INTO message (id, name, content, read) VALUES(NULL, "Guido", "van Rossum", 0)')
        con.commit()

# file2.py 
import sqlite3
import time

con = sqlite3.connect('messages.db')
cur = con.cursor()

def listen():
    messages = cur.execute('SELECT * FROM message WHERE read=0')
    if not messages:
        return False 
    for m in messages: 
        print 'get message ', m
        cur.execute("UPDATE message SET read=1 WHERE id=?", m[0])        
        con.commit()
        print 'update db'
    return True

while True: 
    listen()
    time.sleep(5)

writetoBOT有两个参数:self和{}。 用Testgui实例调用它:

tgui=Testgui(your_master)
tgui.writetoBOT(l)

如果要用Testgui类调用它,仍然需要传递Testgui的实例:

^{pr2}$

您将Testgui声明为类。这被理解为一个骨架或线框(注意,这是一个捷径,而不是现实)。为了使用它,首先需要从这个骨架中创建一个“真实”的对象。在

testgui=Testgui(amaster)

在类中,可以有在类级别应用的方法(绑定函数)。这些方法称为静态方法或类方法。它们必须用Python装饰。在

有关详细信息,请参见http://en.wikipedia.org/wiki/Object_oriented_programming。在

相关问题 更多 >

    热门问题