Как немедленно прервать выполнение указанной функции при нажатии на кнопку?
Нужно, чтобы после нажатия на клавишу «s» или кнопку STOP, выполнение функции mainProc() тут же прерывалось. То есть, например, чтобы эта функция, которая «рисует» курсором квадрат, тут же переставала водить курсором, если в этот момент была нажата кнопка.
Уточняю, что необходимо именно прервать сразу при нажатии кнопки. Вот пример кода, который при нажатии кнопки «d» способен прервать программу, из-за чего движение курсора тут же прекращается. Однако это решение завершает работу всей программы, а нужно прервать выполнение только функции, ну или конкретного потока.
- Вопрос задан 28 янв.
- 387 просмотров
- Вконтакте

- Вконтакте


SoftHardcore, у тебя вызывается 4 раза функция pyautogui.move. Сделай метод, который принимает параметры, которые ты в ней указываешь и перед вызовом pyautogui.move сделай проверку
И вызывай в mainProc этот метод
- Вконтакте
Если вы хотите прерывать код по какому-то событию практически в произвольном месте (в любой момент), то тогда вам необходим объект класса, который будет определять каким функциям сейчас работать (своеобразный scheduler), то есть работать ли основной программе или же работать обработчику нажатия кнопки, движения мыши. В данном случае имеет смысл говорить о вытесняющей многозадачности.
Если же вы не хотите строить сложную кастомную систему, то можете написать, например, асинхронный код (поскольку в основе уже есть определенный scheduler) и реализовать свою логику вытеснения одних задач другими.
- Вконтакте
SoftHardcore, пример того как остановить функцию на «горячую» не выйдет, кроме аварийного завершения потока, но, думаю, вам не это нужно. Самое подходящее решение, на мой взгляд — вы можете разбить программу на очень маленькие функции, между которыми можно проверять было ли события (нажатие кнопки) или нет. Это можно делать даже в одном потоке, но тогда вы можете пропускать события, которые успели начаться и завершиться пока функция выполнялась (если она все же получилась длительная).
Вот пример для двух потоков и mutex’a. Можно также использовать event, вместо mutex.
Также тут есть недостаток, что первый поток может заблокировать mutex, и второй останется в вечном ожидании мьютекса. Это можно исправить если запихать checkEvent в класс, который в своем деструкторе будет разблокировать mutex. Или просто в конце функции проверять, что mutex точно свободен. Также есть проблема многопоточности в python, связаная с GIL, если интересно почитайте.
How to stop a function
My problem is that if a certain condition becomes true (in the function check_winner ) and function end() executes it will go back to computer() or player() because there’s no line that tells the computer to stop executing player() or computer() . How do you stop functions in Python?
5 Answers 5
A simple return statement will ‘stop’ or return the function; in precise terms, it ‘returns’ function execution to the point at which the function was called — the function is terminated without further action.
That means you could have a number of places throughout your function where it might return. Like this:
In this example, the line do_something_else() will not be executed if do_not_continue is True . Control will return, instead, to whichever function called some_function .
This will end the function, and you can even customize the «Error» message:
Above is a pretty simple example. I made up a statement for check_winner using score = 100 to denote the game being over.
You will want to use similar method of passing score into check_winner , using game_over = check_winner(score) . Then you can create a score at the beginning of your program and pass it through to computer and player just like game_over is being handled.
Exit a Function in Python
Every program has some flow of execution. A flow is nothing but how the program is executed. The return statement is used to exit Python’s function, which can be used in many different cases inside the program. But the two most common ways where we use this statement are below.
- When we want to return a value from a function after it has exited or executed. And we will use the value later in the program.
Please enable JavaScript
Here, it returns the value computed by a+b and then stores that value which is 3 , inside the value variable.
- When we want to stop the execution of the function at a given moment.
Here, if the values of either a or b are 0 , it will directly return without calculating the numbers’ sum. If they are not 0 then only it will calculate and return the sum .
Now, if you implement this statement in your program, then depending upon where you have added this statement in your program, the program execution will change. Let’s see how it works.
Implicit Return Type in Python
Suppose we have a function inside which we have written using an if statement, then let’s see how the program behaves.
The solution() function takes no arguments. Inside it, we have a variable called name and then check its value matches the string john using the if statement. If it matches, we print the value of the name variable and then exit the function; otherwise, if the string doesn’t match, we will simply exit it without doing anything.
Here, you might think that since there is no return statement written in the code, there is no return statement present. Note that the return statement is not compulsory to write. Whenever you exit any Python function, it calls return with the value of None only if you have not specified the return statement. The value None means that the function has completed its execution and is returning nothing. If you have specified the return statement without any parameter, it is also the same as return None . If you don’t specify any return type inside a function, then that function will call a return statement. It is called an implicit return type in Python.
Explicit Return Type in Python
Whenever you add a return statement explicitly by yourself inside the code, the return type is called an explicit return type. There are many advantages of having an explicit return type, like you can pass a value computed by a function and store it inside a variable for later use or stop the execution of the function based on some conditions with the help of a return statement and so on. Let’s see an example of the explicit type in Python.
This is a program for finding Fibonacci numbers. Notice how the code is return with the help of an explicit return statement. Here, the main thing to note is that we will directly return some value if the number passed to this function is 2 or lesser than 2 and exit the function ignoring the code written below that. We will only execute our main code (present inside the else block) only when the value passed to this function is greater than 2 .
Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.
Pass, Break and Continue in Python 3
![]()
If you’re new to Python coding, you may have come across pass , break and continue . These words are known as control statements because they are used to perform specific tasks for control flow. In other words, they help tell Python when or for how long to do something, like running a loop, before moving on to something else.
When I first starting coding in Python, I often got confused about these particular keywords (special words that are reserved in Python). Understanding the differences between pass , break and continue can be difficult at first, but it is useful to learn when and how to use them. So without further ado, here is the rundown on pass , break and continue for beginners:
This is probably the simplest of the three, so it will the best one to start with. Essentially, you use pass when you want to do… nothing.
Sounds weird right? Why would we need to do this? Let’s look at a few examples to help illustrate why this might be useful.
In many cases, pass is really just used as a placeholder for code that will eventually be added later. For example, say you are working on a project, and you know you are going to need a function to do something. Maybe you are working on a different part of your code and you don’t want to get caught up in building out the function right now, but you want to have some kind of reminder that you will need that function later, so you define it like so:
The problem with this is that leaving your function empty will give you an IndentationError because once the function is defined, Python is expecting something to be inside it, so it assumes the next line of code should be indented. To stop this from happening, all you need to do is put pass in the function.
This way, you will have an empty function that does nothing, and you can run your code without getting an error. This enables you to build out the skeleton of your program while still maintaining a workflow that you are comfortable with.