使用fileinput找不到文本时如何打印消息?蟒蛇

时间:2020-09-22 18:41:09

标签: python python-3.x discord.py

当我尝试使用fileinput编辑的文本不存在时,如何通过终端或ctx.send(不和谐)返回消息?

基本上,我正在尝试通过检查用户ID是否与“飞行员:”后面的文本匹配来确保该用户(在这种情况下为文件)已经声明了该权限(如果不是),则不能取消声明它,这将导致脚本通过ctx.send()向用户返回一条消息。

我已经尝试过...

@bot.command() #Work in progress
async def unclaim(ctx, *, message=None):

    author = ctx.author.id
    author = '<@'+str(author)+'>'
    mylines = []

    with fileinput.input(cwd+'/jobs/'+message+'.txt', inplace=True) as f:
        for line in f:
            mylines.append(line)
            pilot = mylines[2]
            pilot = pilot.split(':')[1]
            if author != pilot:
                await ctx.send(f'{ctx.author.mention}, you have not claimed this job.')
            else:
                print(line.replace('<@'+str(author)+'>', 'no one'), end='')

收到错误 更新了新错误 我注意到运行unclaim会导致访问的文件被清空。不知道为什么。

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\Owner\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "D:\Projects\dispatch_bot\bot.py", line 98, in unclaim
    pilot = mylines[2]
IndexError: list index out of range

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Owner\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "D:\Projects\dispatch_bot\bot.py", line 45, in on_command_error
    raise error
  File "C:\Users\Owner\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Owner\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Owner\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range

正在访问文本文件...

Leg: KBYS>KSQL
Max Weight/Pax: 0/12
Pilot: no one

1 个答案:

答案 0 :(得分:0)

解决此问题的代码。

@bot.command() #Work in progress
async def unclaim(ctx, *, message=None):

    author = ctx.author.id
    author = ' <@'+str(author)+'>' #need to remove space from front of <@ in text file
    author_is_pilot = False
    mylines = []

    with open(cwd+'/jobs/'+message+'.txt', 'r+') as f:
        for line in f:
            mylines.append(line)
        pilot = mylines[2]
        pilot = pilot.split(':')[1]

    if author == pilot:
        author_is_pilot = True
        with fileinput.input(cwd+'/jobs/'+message+'.txt', inplace=True) as f:
            for line in f:
                print(line.replace(author, ' no one'), end='')
    else:
        await ctx.send(f'{ctx.author.mention}, you have not claimed this job.')

一开始我的代码有两个问题。

  1. (如Pranav所建议),pilot=mylines[2]和for循环中的下一行使我尝试访问的列表超出范围。
  2. 声明工作时,变量author没有考虑空格。 (即飞行员= <@ 238472959> ^

我确实可以使用我最初编写的代码,但可能需要修复上面列出的问题。睡一会儿会测试。如果没有这个问题,我深表歉意。我的印象是,由于我使用的是fileinput,因此限制了with内的工作。