PySimpleGui + Telegram 如何在单独的线程中上传文件?

发布于 2025-01-11 23:04:43 字数 1725 浏览 3 评论 0原文

我正在尝试在线程中上传文件。所以稍后我可以添加带有进度条更新的回调等。

我尝试使用线程和 PySimpleGui 的 perform_long_operation 来做到这一点。 它不是这样工作的。

那么我该怎么做呢?可能我遗漏了一些关于 asyncio 使用的内容。

from pyrogram import Client
from time import sleep
import PySimpleGUI as sg
import asyncio
import random
import sys

api_id = 234242434
api_hash = '324423423'


sg.change_look_and_feel('DarkAmber')

layout = [
    [sg.Text('Password'), sg.InputText(password_char='*', key='password')],
    [sg.Text('', key='status', size=(20, 1))],
    [sg.Button('Submit'), sg.Button('Cancel')]
]

window = sg.Window('TG Send', layout, finalize=True)

client = None

def long_proc():
    client = Client('tg_send', api_id, api_hash)
    window['status'].update('connecting')
    client.connect()
    window['status'].update('started')

    done = False
    while True:
        if not done:
            print('Uploading file')
            window['status'].update('uploading')
            client.send_document('me', document='File.db')
            done = True
            print('Uploading done')
            window['status'].update('uploaded')
        else:
            sleep(1)
    

async def ui():
    while True:
        event, value = window.read(timeout=1)
        if event in (None, 'Cancel'):
            sys.exit()
        
        if event != '__TIMEOUT__':
            print(f"{event=} {value=}")
        
        if event == 'Submit':
            window.perform_long_operation(long_proc, '-FUNCTION COMPLETED-')

        await asyncio.sleep(0)


async def main():
    await asyncio.gather(
        asyncio.create_task(ui()),
        # asyncio.to_thread(long_proc),
        
    )
    

if __name__ == '__main__':
    asyncio.run(main())

I'm trying to upload a file in thread. So later I can add callback with progress bar update etc.

I've tried to do that with threading and PySimpleGui's perform_long_operation.
It is not working this way.

So how do I do it? Probably, I'm missing something about asyncio usage.

from pyrogram import Client
from time import sleep
import PySimpleGUI as sg
import asyncio
import random
import sys

api_id = 234242434
api_hash = '324423423'


sg.change_look_and_feel('DarkAmber')

layout = [
    [sg.Text('Password'), sg.InputText(password_char='*', key='password')],
    [sg.Text('', key='status', size=(20, 1))],
    [sg.Button('Submit'), sg.Button('Cancel')]
]

window = sg.Window('TG Send', layout, finalize=True)

client = None

def long_proc():
    client = Client('tg_send', api_id, api_hash)
    window['status'].update('connecting')
    client.connect()
    window['status'].update('started')

    done = False
    while True:
        if not done:
            print('Uploading file')
            window['status'].update('uploading')
            client.send_document('me', document='File.db')
            done = True
            print('Uploading done')
            window['status'].update('uploaded')
        else:
            sleep(1)
    

async def ui():
    while True:
        event, value = window.read(timeout=1)
        if event in (None, 'Cancel'):
            sys.exit()
        
        if event != '__TIMEOUT__':
            print(f"{event=} {value=}")
        
        if event == 'Submit':
            window.perform_long_operation(long_proc, '-FUNCTION COMPLETED-')

        await asyncio.sleep(0)


async def main():
    await asyncio.gather(
        asyncio.create_task(ui()),
        # asyncio.to_thread(long_proc),
        
    )
    

if __name__ == '__main__':
    asyncio.run(main())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回梦 2025-01-18 23:04:43

以下信息仅适用于 PySimpleGUI 的代码,而不适用于 asyncasyncio

def long_proc():
    client = Client('tg_send', api_id, api_hash)
    window['status'].update('connecting')                   # Wrong call in thread
    client.connect()
    window['status'].update('started')                      # Wrong call in thread

    done = False
    while True:
        if not done:
            print('Uploading file')
            window['status'].update('uploading')            # Wrong call in thread
            client.send_document('me', document='File.db')
            done = True
            print('Uploading done')
            window['status'].update('uploaded')             # Wrong call in thread
        else:
            sleep(1)

执行长操作

此方法使用线程。这意味着您无法从您提供的函数进行任何 PySimpleGUI 调用,但一个函数 Window.write_event_value 除外。

相反,通过调用 window['status'].update(values['-STATUS-']) 来处理事件循环中的事件 -STATUS-

def long_proc():
    client = Client('tg_send', api_id, api_hash)
    window.write_event_value('-STATUS-', 'connecting')
    client.connect()
    window.write_event_value('-STATUS-', 'started')

    done = False
    while True:
        if not done:
            print('Uploading file')
            window.write_event_value('-STATUS-', 'uploading')
            client.send_document('me', document='File.db')
            done = True
            print('Uploading done')
            window.write_event_value('-STATUS-', 'uploaded')
        else:
            sleep(1)

Following information is just for the code about PySimpleGUI and not about async and asyncio.

def long_proc():
    client = Client('tg_send', api_id, api_hash)
    window['status'].update('connecting')                   # Wrong call in thread
    client.connect()
    window['status'].update('started')                      # Wrong call in thread

    done = False
    while True:
        if not done:
            print('Uploading file')
            window['status'].update('uploading')            # Wrong call in thread
            client.send_document('me', document='File.db')
            done = True
            print('Uploading done')
            window['status'].update('uploaded')             # Wrong call in thread
        else:
            sleep(1)

perform_long_operation

This method uses THREADS. This means you CANNOT make any PySimpleGUI calls from the function you provide with the exception of one function, Window.write_event_value.

Instead, handle the event -STATUS- in your event loop by calling window['status'].update(values['-STATUS-']).

def long_proc():
    client = Client('tg_send', api_id, api_hash)
    window.write_event_value('-STATUS-', 'connecting')
    client.connect()
    window.write_event_value('-STATUS-', 'started')

    done = False
    while True:
        if not done:
            print('Uploading file')
            window.write_event_value('-STATUS-', 'uploading')
            client.send_document('me', document='File.db')
            done = True
            print('Uploading done')
            window.write_event_value('-STATUS-', 'uploaded')
        else:
            sleep(1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文