首页 > 解决方案 > 当我在一个函数中返回一个变量并在另一个没有打印的函数中打印它时,怎么会这样?

问题描述

我正在编写一个不和谐机器人,当我编写?start它时,它会不断检查文本文件是否更改,如果发生更改,它会获取文本文件的最后一行并将其保存到变量avatarid中。当我avatarid在函数中打印时,look如果我写print(avatarid)它会打印头像ID,但是,如果我return avatarid在名为start(一个机器人命令)的异步函数中打印它,它不会打印任何东西。

我的代码:

class Watcher(object):
    running = True
    refresh_delay_secs = 1

    # Constructor
    def __init__(self, watch_file, call_func_on_change=None, *args, **kwargs):
        self._cached_stamp = 0
        self.filename = watch_file
        self.call_func_on_change = call_func_on_change
        self.args = args
        self.kwargs = kwargs

    # Look for changes
    def look(self):
        stamp = os.stat(self.filename).st_mtime
        if stamp != self._cached_stamp:
            self._cached_stamp = stamp
            # File has changed, so do something...
            with open("\\Program Files (x86)\\Steam\\steamapps\\common\VRChat\\PythonLogger.txt", "r") as file:
                for last_line in file:
                    pass
            avatarid_old = last_line
            avatarid = avatarid_old.replace("\n", "")
            #avatar_id = self.look()
            #print(avatarid)
            if self.call_func_on_change is not None:
                self.call_func_on_change(*self.args, **self.kwargs)
            return avatarid

    # Keep watching in a loop        
    def watch(self):
        while self.running: 
            try: 
                # Look for changes
                time.sleep(self.refresh_delay_secs) 
                avatarid = self.look() 
                #avatarid = self.look()
            except KeyboardInterrupt: 
                print('\nDone') 
                break 
            except FileNotFoundError:
                # Action on file not 
                pass
           # except: 
                #print('Unhandled error: %s' % sys.exc_info()[0])


def custom_action(text):
    print(text)
watch_file = '\\Program Files (x86)\\Steam\\steamapps\\common\VRChat\\PythonLogger.txt'



#start command
@bot.command(name='start')
async def start(ctx):
    """starts the bot"""
    await ctx.message.delete()
    watcher = Watcher(watch_file, custom_action, text='File Changed!')  # also call custom action function
    watcher.watch()  # start the watch going
    #avatarid = self.look()

    print(avatarid)
    av_id = avatarid.strip()
    response = requests.post("https://vrcpanel.com/test/vrcadownload", data={"avatarid":av_id, "login":"Download+VRCA"}, allow_redirects=False)

    url = f'https://api.vrchat.cloud/api/1/avatars/{avatarid}?apiKey=JlE5Jldo5Jibnk5O5hTx6XVqsJu4WJ26'
    req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    webpage = urlopen(req)
    data = json.load(webpage)
    #await ctx.send(data['name'])
    check_description = ''
    if data['description'] == data['name']:
        check_description = "Avatar has no description."
    else:
        check_description = data['description']

    embed = discord.Embed(title=data['name'], description=check_description, color=0x0000FF)
    embed.set_image(url=data['thumbnailImageUrl'])
    embed.add_field(name="Download:", value=(response.headers["Location"]))
    embed.add_field(name='Uploaded:', value=data['created_at'])
    embed.add_field(name='Status:', value=data['releaseStatus'])
    embed.add_field(name='Author:', value=data['authorName'])
    await ctx.send(embed=embed)  

标签: python

解决方案


avatarid变量是 Watcher 类的内部变量,因此无法在其外部访问。还有,这个self变量一般用来标识一个类自己的功能。这意味着您必须将函数指向对象,而不是“自我”。尝试纠正#avatarid = self.look()avatarid = watcher.look()

解决此问题的另一种方法是使用self变量在类中添加头像属性,例如:

self.avatarid = avatarid_old.replace("\n", "")

然后,您可以再次使用您的观察者对象调用它:

print(watcher.avatarid)

推荐阅读