简体   繁体   English

Python 同时执行功能

[英]Python execute functions simultaneously

I know that this question has been asked multiple times, however I couldn't solve the issue by going over the answers.我知道这个问题已被多次问过,但是我无法通过查看答案来解决问题。 I need help.我需要帮助。 I wrote this telegram bot in Python in order to practice, and everything works ok, however yesterday I tried to implement an "uptime" timer, I wrote the function and on its own if works, however when I call it in the main file it will override everything else and the bot will not work.为了练习,我在 Python 中编写了这个电报机器人,一切正常,但是昨天我尝试实现一个“正常运行时间”计时器,我编写了 function 并且它自己写了如果可以工作,但是当我在主文件中调用它时将覆盖其他所有内容,机器人将无法工作。 Furthermore, I tried to implement threading and multithreading and pretty much everything I could find online, however it still did not work.此外,我尝试实现线程和多线程以及几乎所有我能在网上找到的东西,但它仍然不起作用。 I think that I'm doing something wrong.我认为我做错了什么。 I'm providing you with the code that I have, but I have removed the threading section from it.我正在为您提供我拥有的代码,但我已从中删除了线程部分。

Timer function定时器 function

import time
import os
import Responses


def cls():
    os.system('cls' if os.name == 'nt' else 'clear')


def uptime():
    days = 0
    hours = 0
    minutes = 0
    seconds = 0

    while True:
        time.sleep(1)
        seconds += 1

        if seconds > 59:
            seconds = 0
            minutes += 1

        if minutes > 59:
            minutes = 0
            hours += 1

        if hours > 23:
            hours = 0
            days += 1

        cls()
        print(f"{Responses.bot_name} has started...")
        print(f"Uptime {days}d:{hours}h:{minutes}m:{seconds}s")

Main Bot file主要机器人文件

import os
import telebot
import Gif
import Responses as R
import Weather
from dotenv import load_dotenv
import timer


load_dotenv()

bot_name = R.bot_name

TELEGRAM_KEY = os.getenv('TELEGRAM_KEY')
bot = telebot.TeleBot(TELEGRAM_KEY, parse_mode=None)

print(f"{bot_name} Started...")


@bot.message_handler(commands=['start'])
def greet(message):
    photo = open(r"Bot Demo.png", 'rb')
    bot.send_message(message.chat.id, f"Hi {message.chat.first_name}, my name is <b>{bot_name}</b>!", parse_mode='html')
    bot.send_photo(message.chat.id, photo, caption="This is me! \nI can send Pictures!")
    bot.send_message(message.chat.id, "Use <i>/help</i> to find out what else I can do!", parse_mode='html')


@bot.message_handler(commands=['help'])
def help(message):
    bot.send_message(message.chat.id, "Hi I'm a <b>DEMO</b> Bot!"
                                      "\nYou can greet me and I'll <b>respond</b>."
                                      "\nYou can ask me about the <b>time</b> and the <b>date</b>."
                                      "\nYou can ask me to tell you a <b>joke</b>."
                                      "\nYou can ask for a <b>gif</b> and you will receive a random gif from the API."
                                      "\nYou can use <i>/weather</i> to get the <b>Weather</b>."
                                      "\nYou can use <i>/gif</i> to get a <b>GIF</b> from a specific category."
                                      "\nYou can also use <i>/info</i> to get more <b>information</b> about my creator.", parse_mode='html')


@bot.message_handler(commands=['info'])
def info(message):
    bot.send_message(message.chat.id, "Hi, my name is Kaloian Kozlev and I am the creator of this bot."
                                      "\nIf you need a Bot for your social media, "
                                      "you can contact me on kbkozlev@gmail.com")


@bot.message_handler(commands=['gif'])
def gif(message):
    sent = bot.send_message(message.chat.id, "If you want a specific GIF "
                                             "\nenter <search_term>"
                                             "\nexample: cat")
    bot.register_next_step_handler(sent, condition)


def condition(message):
    q = str(message.text).lower()
    bot.send_video(message.chat.id, Gif.search_gif(q), caption=f"Here is a picture of a random {q}")


@bot.message_handler(commands=['weather'])
def weather(message):
    sent = bot.send_message(message.chat.id, "Enter City name:")
    bot.register_next_step_handler(sent, city)


def city(message):
    q = str(message.text).lower()
    bot.send_message(message.chat.id, Weather.get_weather(q))


@bot.message_handler()
def handle_message(message):
    text = str(message.text).lower()
    response = R.sample_responses(text)
    bot.send_message(message.chat.id, response)
    if "gif" in text:
        bot.send_video(message.chat.id, Gif.get_gif(), caption="I'm using an API to get this GIF")

timer.uptime()
bot.polling()

Maybe try out threading or multiprocessing if you haven't already.如果您还没有,也许可以尝试线程或多处理

Threading Example - from this site线程示例- 来自此站点

import threading

def function_1():
   print("Inside The Function 1")

def function_2():
   print("Inside The Function 2")

# Create a new thread
Thread1 = threading.Thread(target=function_1)

# Create another new thread
Thread2 = threading.Thread(target=function_2)

# Start the thread
Thread1.start()

# Start the thread
Thread2.start()

# Wait for the threads to finish
Thread1.join()
Thread2.join()

print(“Done!”)

This is a wild guess, because you didn't show your threading code.这是一个疯狂的猜测,因为您没有显示您的线程代码。 A common mistake when using the threading module, is executing your function in the call, rather than just passing the name.使用线程模块时的一个常见错误是在调用中执行 function,而不仅仅是传递名称。 Perhaps you did this:也许你这样做了:

threading.Thread(target=myfunction())

Instead of this:而不是这个:

threading.Thread(target=myfunction)

It's a common error.这是一个常见的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM