【问题标题】:Import variable from pythonscript --> solve caused TypeError从 pythonscript 导入变量 --> 解决导致的 TypeError
【发布时间】:2020-07-31 07:41:02
【问题描述】:

我一直在尝试使用gtts 构建一个speech-recognition 应用程序。我现在要做的是使用另一个 python 脚本中的变量,这样我就可以更新一个 tk 标签。我试图将我的代码放在一个类的结构中以访问该变量。我添加了一个较小的程序来展示我的问题。 (这些程序要同时运行) 我是 Python 的初学者,所以我希望你们能教我如何做得更好。 :) 提前谢谢你!

错误:

S = SuperAssistant()
TypeError: __init__() missing 1 required positional argument: 'audio'

展示我的问题的基本示例:

from try_access_var import myfunction 

print(myfunction.audio)

然后在我的另一个名为 try_access_var 的 pyscript 中:

def myfunction():
    audio = 1

(我想在其中实施我可能得到的解决方案的程序)

`from gtts import gTTS
import speech_recognition as sr
from playsound import playsound
import os
import re
import webbrowser
from tkinter import *
import smtplib
import requests
import sys
import subprocess
from subprocess import Popen
import time
import datetime as dt
from datetime import timedelta
import keyboard
import mouse
import pyaudio
import tkinter as tk
from tkinter import filedialog, Text
import csv

注意“Class SuperAssistant”属于代码

类超级助理:

def __init__(self):

    self.audio = audio
    
    

def talkToMe(self):
    "speaks audio passed as argument"

    #SuperAssistant.audio = audio
    print(self.audio)
    
    tts = gTTS(text=audio, lang='en')
    tts.save("good.mp3")
    #os.system("cd C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHAR//desktopAssistant-master")
    #os.system("python -i C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHAR//desktopAssistant-master//tkinter_samentha_tricks.py")
    #os.system("python -i tkinter_samentha_tricks.py")
    #force it to have no console
    DETACHED_PROCESS = 0x00000008
    subprocess.Popen("python -i tkinter_samentha_tricks.py") #creationflags=DETACHED_PROCESS)
    while playsound("good.mp3"):
        pass
    os.remove("good.mp3")


        

    #print(audio)
    #for line in audio.splitlines():
     #   os.system("say " + audio)

    #use the system's inbuilt say command instead of mpg123
    #text_to_speech = gTTS(text=audio, lang='en')
    #text_to_speech.save('audio.mp3')
    #os.system('mpg123 audio.mp3')



def myCommand(self, x):
    "listens for commands"

    r = sr.Recognizer()
    #mic_version= open("C:/Users/johan/OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen/DATA_SHARE/desktopAssistant-master/choose_mic_text.txt", "r")
    #mic_integer=mic_version
    #mic = sr.Microphone(device_index=mic_integer)

    with sr.Microphone() as source:
        print('Ready...')
        r.pause_threshold = 1
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)

    if x == 1:
        try:
            command = r.recognize_google(audio).lower()
            #talkToMe('You said: ' + command + '\n')
            #add silent mode. for now: print only
            print('You said: ' + command + '\n')
        #loop back to continue to listen for commands if unrecognizable speech is received
        except sr.UnknownValueError:
            print('Your last command couldn\'t be heard')
            command = SuperAssistant.myCommand(1);

        return command


        if x == 2:
            try:
                command02 = r.recognize_google(audio).lower()
                #talkToMe('You said: ' + command + '\n')
                #add silent mode. for now: print only
                print('You said: ' + command02 + '\n')
            #loop back to continue to listen for commands if unrecognizable speech is received
            except sr.UnknownValueError:
                print('Your last command couldn\'t be heard')
                command02 = SuperAssistant.myCommand(2);

            return command02
        
        if x == 3:
            try:
                command03 = r.recognize_google(audio).lower()
                #talkToMe('You said: ' + command + '\n')
                #add silent mode. for now: print only
                print('You said: ' + command03 + '\n')
            #loop back to continue to listen for commands if unrecognizable speech is received
            except sr.UnknownValueError:
                print('Your last command couldn\'t be heard')
                command03 = SuperAssistant.myCommand(3);

            return command03

        if x == 4:
            try:
                command04 = r.recognize_google(audio).lower()
                #talkToMe('You said: ' + command + '\n')
                #add silent mode. for now: print only
                print('You said: ' + command04 + '\n')
            #loop back to continue to listen for commands if unrecognizable speech is received
            except sr.UnknownValueError:
                print('Your last command couldn\'t be heard')
                command04 = SuperAssistant.myCommand(4);

            return command04

        if x == 5:
            try:
                command05 = r.recognize_google(audio).lower()
                #talkToMe('You said: ' + command + '\n')
                #add silent mode. for now: print only
                print('You said: ' + command05 + '\n')
            #loop back to continue to listen for commands if unrecognizable speech is received
            except sr.UnknownValueError:
                print('Your last command couldn\'t be heard')
                command05 = SuperAssistant.myCommand(5);

            return command05

        if x == 6:
            try:
                command06 = r.recognize_google(audio).lower()
                #talkToMe('You said: ' + command + '\n')
                #add silent mode. for now: print only
                print('You said: ' + command06 + '\n')
            #loop back to continue to listen for commands if unrecognizable speech is received
            except sr.UnknownValueError:
                print('Your last command couldn\'t be heard')
                command06 = SuperAssistant.myCommand(6);

            return command06
    

    def time_greeting():
        if 12 > dt.datetime.now().hour:
            SuperAssistant.talkToMe('Good morning sir.')
        elif 12 == dt.datetime.now().hour:
            SuperAssistant.talkToMe('It is high noon, hope you are ready for your duel!')
        elif (12 < dt.datetime.now().hour) and (18 > dt.datetime.now().hour):
            SuperAssistant.talkToMe('Good afternoon sir.')
        elif 18 < dt.datetime.now().hour:
            SuperAssistant.talkToMe('Good evening sir.')

    def time_bye():
        if 12 > dt.datetime.now().hour:
            SuperAssistant.talkToMe('wish you a nice morning sir.')
        elif 12 == dt.datetime.now().hour:
            SuperAssistant.talkToMe('wish you a good lunce sir.!')
        elif (12 < dt.datetime.now().hour) and (18 > dt.datetime.now().hour):
            SuperAssistant.talkToMe('wish you a good afternoon sir.')
        elif 18 < dt.datetime.now().hour:
            SuperAssistant.talkToMe('wish you good evening sir.')


    def welcome():
        
        SuperAssistant.talkToMe('My systems are booting up. Systems successfully booted!')
        SuperAssistant.time_greeting()
        SuperAssistant.talkToMe('How should I call you? Please tell me your name.')
        global name
        name = SuperAssistant.myCommand(1)
        SuperAssistant.talkToMe('Nice to meet you ' + name +'.')

        file=open("C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHARE//desktopAssistant-master//userprofiles.txt", "r") 

        with open("C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHARE//desktopAssistant-master//userprofiles.txt", "r") as profiles:
        
            for line in profiles:
                if name in line:
                    pass
        
    
        for profiles in file.readlines():
            print(profiles)
            
        if name in profiles:
            SuperAssistant.talkToMe('welcome back.')
            file.close()
        else:
            SuperAssistant.talkToMe('Should I create a new profile?')
            profilcreation=myCommand(2)
                
            if 'yes' in profilcreation:
            
                #questions to ask to create new profil
                SuperAssistant.talkToMe('I am going to ask you some questions...')
                        
                SuperAssistant.talkToMe('What is your favorite color?')
                question01_profilcreation=myCommand(3)
                        
                SuperAssistant.talkToMe('What is your favorid food?')
                question02_profilcreation=myCommand(3)
                        
                SuperAssistant.talkToMe('When were you born?')
                question03_profilcreation=myCommand(3)

                file=open("C:/Users/johan/OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen/DATA_SHARE/desktopAssistant-master/userprofiles.txt", "a") 

                
                file.write('\n'+'['+'"'+name+'"'+','+'"'+question01_profilcreation+'"'+','+'"'+question02_profilcreation+'"'+','+'"'+question03_profilcreation+'"'+']')

                    
                    

            
            elif 'no' in profilcreation:
                SuperAssistant.talkToMe('profilcreation denied')

        file.close()
        
        return name
        

    def load(element):

        with open("C://Users//johan//OneDrive - Departement Bildung, Kultur und Sport Kanton Aargau-7988362-Kantonsschule Zofingen//DATA_SHARE//desktopAssistant-master//userprofiles.txt", "r") as profiles:

            for line in profiles:
                if name in line:
                    
                    hole_item=line
                    #hole_item.append(line)
                    #profil_item=hole_item[element]
                    profil=hole_item.split(",")
                    print(profil)
                    profiles.close()
                    
                    return profil[element]
                    
            all_the_lines = profiles.readlines()
            items = []
            for i in all_the_lines:
                items.append(i)
                print(items)


    def assistant(command):
        "if statements for executing commands"
        
        global name

        global check

       
        if 'samantha' in command:

            if (check == 0):
                check = 1
                SuperAssistant.welcome()
            else:
                SuperAssistant.talkToMe("What can I do for you")

            
            command02 = SuperAssistant.myCommand(2)
            
            if 'open reddit' in command02:
                reg_ex = re.search('open reddit (.*)', command02)
                url = 'https://www.reddit.com/'
                if reg_ex:
                    subreddit = reg_ex.group(1)
                    url = url + 'r/' + subreddit
                webbrowser.open(url)
                print('Done!')
                    

            elif 'open youtube' in command02:
                reg_ex = re.search('open website (.+)', command02)
                print(command02)
                song_title=command02[12:]
                print(song_title)
                url='https://www.youtube.com/results?search_query='+song_title
                webbrowser.open(url)
                talkToMe('Done!')
                
                command03 = SuperAssistant.myCommand(3)
                
                if 'play' in command03:
                    keyboard.press_and_release('tab','tab')
                    keyboard.press_and_release('enter')

                    command04 = SuperAssistant.myCommand(4)

                    if 'stop' in command04:
                        keyboard.press_and_release('space')
                        command04 = SuperAssistant.myCommand(4)

                    elif 'continue' in command04:
                        keyboard.press_and_release('space')
                        command04 = myCommand(4)
                    elif 'exit' in command03:
                        talkToMe('exit')
                        command = SuperAssistant.myCommand(1)

            elif 'help' in command02:
                talkToMe('I\'ve got some information for you.')`

这是我在函数/类末尾的代码:

if __name__ == "__main__":
    S = SuperAssistant()
    S.talkToMe('I am ready for your command')
    


#loop to continue executing multiple commands
    while True:
        SuperAssistant.assistant(SuperAssistant.myCommand(1))

我用 subprocess.Popen(....) 打开的小程序的代码(显示 tk 窗口)

#importing the class/function
from desktopAssistant_wakeup import SuperAssistant
from tkinter import *

#printing out imported variable (if classes are used: object)

print(#way to print audio)

【问题讨论】:

  • self 是对类实例的引用,它可用作类内部方法的第一个参数。
  • 是的。你有什么建议:)
  • 我更新了我的答案,并包含了一个使用类和实例属性的示例。

标签: python-3.x class tkinter python-import attributeerror


【解决方案1】:

SuperAssistent 没有名为 audio 的类属性。为此,您必须将其设置在课堂上的某个位置。例如,您可以在talkToMe 中执行SuperAssistent.audio = audio 之类的操作。

您是否故意只使用类方法而不实例化SuperAudio?如果不是这种情况,您应该添加一个构造函数并添加self 作为所有非类方法的第一个参数。 如果是这样的话,我建议通过 Python 类/对象的介绍,例如 this one on w3schools

更新:

这是一个设置和访问类和实例属性的示例,其中包含用于脚本和类定义的拆分文件:

example.py:

class Foo():
    class_attribute = 'class attribute: initial value'

    def __init__(self):
        self.instance_attribute = \
            'instance attribute ({:X}): initial value'.format(id(self))

    def do_something(self = None):
        Foo.class_attribute = 'class_attribute: modified value'
        if self is not None:
            self.instance_attribute = \
                'instance attribute ({:X}): modified value'.format(id(self))

script.py

#!/usr/bin/env python3

from example import Foo

a = Foo()
b = Foo()

print(Foo.class_attribute)
print(a.instance_attribute)
print(b.instance_attribute)

print('\nChanging attributes..\n')
Foo.do_something()
a.do_something()
b.do_something()

print(Foo.class_attribute)
print(a.instance_attribute)
print(b.instance_attribute)

执行script.py 会给出以下输出(请注意,ID 在机器和执行之间会发生变化:

class attribute: initial value
instance attribute (7F640ACF56A0): initial value
instance attribute (7F640AC2AB50): initial value

Changing attributes..

class_attribute: modified value
instance attribute (7F640ACF56A0): modified value
instance attribute (7F640AC2AB50): modified value

【讨论】:

  • 感谢您的回答!在我的原始代码中,我没有使用类。我想我可以尝试添加一个不正确的类来更接近解决方案。您认为这里真的需要一门课程吗,或者我可以尝试解决它吗?
  • 一般来说,你可以在没有类的情况下实现一切,但是使用类的面向对象的方法可以帮助构建程序并封装函数和数据。
  • 感谢您的帮助,但将“SuperAssistant.audio = audio”添加到“talkToMe”并不起作用,所以我尝试按照您的说法完成课程。我添加了 __init__() 函数,但问题是我不想创建一个全新的对象。我想使用变量“audio”并创建一个可以通过另一个脚本访问的对象。
  • @JohannesZimmermann:具体是什么不起作用?你得到什么样的错误?也许您可以更新您的问题并添加新代码。关于实例化对象的方法:你为什么不在脚本中实例化你需要的对象(当然你仍然需要导入类定义)。
  • 关于您的问题:我不知道实例化对象的最佳位置在哪里......
猜你喜欢
  • 2018-10-19
  • 2017-02-20
  • 2020-09-16
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
相关资源
最近更新 更多