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

时间:2014-01-31 12:59:41

标签: python function variables arguments

我很难将变量从一个函数传递到另一个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)

这是sceond文件:

# TestGUI_2.py

from TestGUI import Testgui

class Tracker:
    def __init__(self):
       pass
    def drive(self,cords, cords1):
       while( cords >= 320):        
           l='l'
           Testgui.writetoBOT(l)      # This is the problem line 

TypeError:必须使用TestGUI实例作为第一个参数调用未绑定方法writetoBOT()(改为使用str实例)

3 个答案:

答案 0 :(得分:4)

writetoBOT有两个参数:selfinstruct。 使用Testgui实例调用它:

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

如果您想使用Testgui课程进行调用,则仍需要传递Testgui的实例:

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

答案 1 :(得分:0)

或者,您可以为这两个脚本创建公共空间,它由数据库 - 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)

答案 2 :(得分:0)

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

testgui=Testgui(amaster)

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

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

相关问题