python - 当我在一个函数中返回一个变量并在另一个没有打印的函数中打印它时,怎么会这样?
问题描述
我正在编写一个不和谐机器人,当我编写?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)
解决方案
该avatarid
变量是 Watcher 类的内部变量,因此无法在其外部访问。还有,这个self
变量一般用来标识一个类自己的功能。这意味着您必须将函数指向对象,而不是“自我”。尝试纠正#avatarid = self.look()
为avatarid = watcher.look()
解决此问题的另一种方法是使用self
变量在类中添加头像属性,例如:
self.avatarid = avatarid_old.replace("\n", "")
然后,您可以再次使用您的观察者对象调用它:
print(watcher.avatarid)
推荐阅读
- selenium - org.openqa.selenium.os.OsProcess checkForError 和 org.apache.commons.exec.ExecuteException:进程因 Selenium ChromeDriver 错误而退出
- wix - WiX 通过属性静默安装条件
- c++ - 带有 enable_if 和重载的 SFINAE
- symfony - 如何在 symfony 4.2 中根据子域设置默认数据库
- ffmpeg - 在ffmpeg中将RTSP流连续保存到具有特定长度(10分钟)的多个mp4文件中
- arrays - 数组如何通过Swift按多个属性排序?
- java - 无法加载 admob 广告错误:3 ERROR_CODE_NO_FILL
- php - 将数据保存到数据库后发送电子邮件
- kubernetes - kubectl 补丁部署导致 'The "" is invalid'
- android - 与动态集内容视图的数据绑定