Python запуск скрипта в фоновом режиме windows

On Windows, you can use pythonw.exe in order to run a python script as a background process:

Python scripts (files with the extension .py) will be executed by
python.exe by default. This executable opens a terminal, which stays
open even if the program uses a GUI. If you do not want this to
happen, use the extension .pyw which will cause the script to be
executed by pythonw.exe by default (both executables are located in
the top-level of your Python installation directory). This suppresses
the terminal window on startup.

For example,

C:\ThanosDodd\Python3.6\pythonw.exe C:\\Python\Scripts\moveDLs.py

In order to make your script run continuously, you can use sched for event scheduling:

The sched module defines a class which implements a general purpose
event scheduler

import sched
import time

event_schedule = sched.scheduler(time.time, time.sleep)

def do_something():
    print("Hello, World!")
    event_schedule.enter(30, 1, do_something, (sc,))

event_schedule.enter(30, 1, do_something, (s,))
event_schedule.run()

Now in order to kill a background process on Windows, you simply need to run:

taskkill /pid processId /f

Where processId is the ID of the process you want to kill.

Let us see how to run a Python program or project in the background i.e. the program will start running from the moment device is on and stop at shut down or when you close it. Just run one time to assure the program is error-bug free

One way is to use pythonw, pythonw is the concatenation of python+without terminal window, i.e. run python without terminal window. You can use it by running the following line on the terminal:

pythonw <nameOfFile.py>

Here’s the background.py is the file:

In Linux and mac, for running py files in the background you just need to add & sign after using command it will tell the interpreter to run the program in the background  

python filename.py & 

It will run the program in the background also simultaneously you can use a terminal. There will process id for the background process, if you want you can kill process also by using as you can’t just kill it by CTRL+C , To kill it, open another terminal session and use the command

kill -9 {{id got after }} &

kill is abbreviated for killing process while -9 used to tell to kill it immediately, the corresponding status will be updated. In order to get your output, you can flush it up in a file  by using 

python filename.py > filenameToFlush &

It will be generating output i.e. flushing output in the file but it’s updated in the buffer memory, you have to wait for the termination of the program to reflect output in a hard disk file. To resolve this, you just need to tell python interpreter that don’t use buffered memory steps:

End/kill currently running the file

Now use utility 

 python -u filename.py > FileToFlush &

It will directly put the output in the file you have selected.

If you close terminal before the end of the program, all processes executed by the terminal will stop, A hangup situation is arising in order to counter problem you need to use nohup command as shown below nohup will assure that process is running till the end whether you close parent terminal. nohup stands for no hangup 

nohup python -u filename.py 

Now you don’t need to flush output in any file as nohup utility generates a file named nohup.out while executing. It will be like log file. The name of the output fill generated by nohup will reflect on. To terminate this execution you will need ID process, There is no problem if you can remember or if you can’t, you need to search for file Just use following command

ps ax | grep filename.py

grep is for pattern searching, it will be reflecting process id on terminal just kill it by using kill -9 ID. Now the process is terminated

Last Updated :
21 Aug, 2020

Like Article

Save Article

In this article, you will learn to run Python Script Constantly in the Background. I’ll show you a variety of methods for keeping Python scripts running in the background on various platforms.

The Python scripting language (files with the extension.py) is run by the python.exe program by default. This application launches a terminal window, which remains open even if the program utilizes a graphical user interface (GUI).

If you do not want this to happen, use the extension.pyw, which will cause the script to be executed by pythonw.exe by default. This prevents the terminal window from appearing when the computer is first booted.

Let us see in the below example codes how you can run Python Script Constantly In Background.

In Python, you have a library named sched[1] that acts as a Scheduler and allows you to run a script or program in Python continuously. Events can be scheduled using the scheduler class’s generic interface. When it comes to dealing with the “outside world,” two functions are needed: timefunc, which is callable without parameters and returns a number.

Let us see in the below example code the usage of sched to run Python script constantly.

import sched
import time

schedulerTest = sched.scheduler(time.time, time.sleep)

def randomFunc(test = 'default'):
    print("Testing Scheduler to Run Script Constantly.")
    schedulerTest.enter(30, 1, randomFunc, ('checkThis',))

schedulerTest.enter(30, 1, randomFunc, ('TestThis',))
schedulerTest.run()

Output:

Testing Scheduler to Run Script Constantly.
Testing Scheduler to Run Script Constantly.

If you are going to use the above code, and add the function that you want to run constantly then you can use the scheduler library.

2. Using the time.sleep() Function To Run Script repeatedly

So, if you do not want to use the above code and just want to run your script repeatedly then you can use the time.sleep() function. This function allows your script to keep running after sleeping for a certain amount of time.

Let see in the below example code the usage of time.sleep() function to run Python Script Repeatedly.

import time

while True:
   def randomFunctionYouWantToKeepRunning():
       print("Testing To Run Script in Background Every 10 secs.")
  randomFunctionYouWantToKeepRunning()
  time.sleep(10)

Output:

Testing To Run Script in Background Every 10 secs.
Testing To Run Script in Background Every 10 secs.

As you can see using the above code, I was able to run the script constantly after every 10 seconds. Based on your usage and after how much time you want the program to re-run you can change the time and then re-run the script.

How To Run Python Script In Background In Linux

You can use the below code on your terminal command line to run the Python Script in the background in Linux. You can also use the code described above to run the Python script constantly.

First, add a Shebang line in your Python Script using the below code.

#!/usr/bin/env python3

If you have numerous versions of Python installed, this path is required to ensure that the first Python interpreter listed in your $$PATH environment variable is taken into consideration. Your Python interpreter’s location can alternatively be hardcoded, although this is less flexible and less able to be used on different machines.

Now run the below command to make the Shebang executable.

chmod +x yourPythonScriptName.py

If you use no hangup, the application will continue to execute in the background even if your terminal is closed.

nohup /path/to/yourPythonScriptName.py &

or 

nohup python /path/to/test.py &

Here & is used as this will tell the operating system to put this process to run in the background.

How To Run Python Script In Background In Windows

If you want to run any Python script in Background in Windows operating System then all you are required to do is to rename the extension of your existing Python script that you want to run in background to ‘.pyw’.

Once you have re-named it then you can run the Python Script and it will start executing in the background. To Terminate the program that started running in the background you will require to use the below command.

TASKKILL /F /IM pythonw.exe

Wrap Up

I hope you got your answer and learned about how to run Python Scripts Constantly In the Background Of Windows, Linux or MacOS. I have discussed two methods and you can use any two methods that work perfectly for you.

Let me know in the comment section if you know any better method than the one discussed above, I will be happy to add it here. Also, let me know if you have any issues related to the above code.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How To Convert Python String To Array
  2. Code Example: How To Check If Set Is Empty In Python
  3. Code Examples – Write A List To CSV Using Python
  4. Code Example: Loop Back To The Beginning Of A Program
  5. How To Do Nothing In An If Statement Python
  6. Code Example: Remove The First Item From List Python
  7. 4 Ways To Loop Through List With Index Using Python
  8. Code Examples: Multiply In Python

Запуск Python скрипта в фоновом режиме через IDLE

IDLE (среда разработки для языка программирования Python) является одним из самых популярных инструментов для разработки программ на Python. Он предлагает удобный интерфейс, позволяющий быстро и эффективно разрабатывать и отлаживать свои программы.

Однако одной из проблем, с которой многие сталкиваются при использовании IDLE, является то, что он не позволяет запускать скрипты в фоновом режиме. Это означает, что при каждом запуске скрипта, IDLE будет блокирован и недоступен для выполнения других задач.

В этой статье мы рассмотрим несколько способов обойти эту ограничение и запустить скрипт в фоновом режиме через IDLE.

1. Использование командной строки

Первым способом является использование командной строки для запуска скрипта. Для этого откройте командную строку и перейдите в папку, где находится ваш скрипт. Затем выполните следующую команду:

python script_name.py

Где `script_name.py` — имя вашего скрипта. Это запустит скрипт в фоновом режиме, и вы сможете продолжать работу в IDLE без блокировки.

2. Создание отдельного потока

Еще одним способом является создание отдельного потока для выполнения скрипта. Для этого вы можете использовать стандартную библиотеку threading в Python. Вот пример, показывающий, как это можно сделать:

from threading import Thread
import time

def my_script():
    # Ваш код здесь
    time.sleep(10)  # Пример работы скрипта в течение 10 секунд

thread = Thread(target=my_script)
thread.start()

В этом примере мы создаем новый поток, который выполняет функцию `my_script`. Вы можете поместить свой код внутри этой функции. После запуска потока вы сможете продолжать работу в IDLE без блокировки.

3. В использовании фреймворков

Некоторые фреймворки, такие как Flask или Django, предлагают свои собственные способы запуска Python-скриптов в фоновом режиме. Это особенно полезно, если вы разрабатываете веб-приложение на Python.

Например, в Flask вы можете использовать расширение Flask-Script, чтобы запустить свою программу в фоновом режиме. Вот пример кода:

from flask import Flask
from flask_script import Manager

app = Flask(__name__)
manager = Manager(app)

@manager.command
def my_script():
    # Ваш код здесь

if __name__ == '__main__':
    manager.run()

Вы можете запустить эту программу из командной строки следующей командой:

python script_name.py my_script

Где `script_name.py` — имя вашего скрипта, а `my_script` — имя задачи, которую вы хотите запустить в фоновом режиме.

Подводя итог, хотя IDLE не предоставляет встроенного способа запуска Python-скриптов в фоновом режиме, существуют несколько альтернативных решений. Вы можете использовать командную строку, создавать отдельные потоки или использовать фреймворки, чтобы достичь этой функциональности. Имейте в виду, что каждый из этих способов имеет свои преимущества и ограничения, поэтому выбор зависит от ваших конкретных потребностей и предпочтений.

Конечно, я могу помочь с этим! Запуск Python скрипта в фоновом режиме на операционной системе Windows можно выполнить несколькими способами. Вот некоторые из них:

  1. Использование командной строки:

    • Шаг 1: Откройте командную строку, нажав Win + R, введите «cmd» и нажмите Enter.
    • Шаг 2: Перейдите в каталог, где находится ваш Python скрипт, с помощью команды cd. Например, если ваш скрипт находится в папке «C:Scripts», выполните команду cd C:Scripts.
    • Шаг 3: Запустите скрипт, используя команду python script.py, где «script.py» — имя вашего скрипта.
    • Шаг 4: Чтобы скрипт продолжал выполняться после закрытия командной строки, добавьте pythonw перед командой запуска скрипта. Например, pythonw script.py.
    • Шаг 5: Закройте командную строку. Ваш скрипт будет продолжать выполняться в фоновом режиме.
  2. Использование планировщика задач:

    • Шаг 1: Нажмите Win + R, введите «taskschd.msc» и нажмите Enter, чтобы открыть Планировщик задач Windows.
    • Шаг 2: Щелкните правой кнопкой мыши на «Планировщик задач» в левой панели и выберите «Создать задачу».
    • Шаг 3: Введите имя для задачи и, при необходимости, описание.
    • Шаг 4: Перейдите на вкладку «Действия» и нажмите «Создать».
    • Шаг 5: Выберите «Запуск программы» и укажите путь к исполняемому файлу Python (python.exe).
    • Шаг 6: В поле «Аргументы» укажите путь к вашему скрипту (script.py).
    • Шаг 7: Перейдите на вкладку «Срабатывания» и настройте график выполнения задачи.
    • Шаг 8: Нажмите «ОК», чтобы сохранить задачу. Теперь ваш скрипт будет выполняться в фоновом режиме согласно заданному графику.
  3. Использование сторонних инструментов:
    Существуют сторонние инструменты, которые облегчают запуск Python скриптов в фоновом режиме на Windows, такие как «pywinauto» или «pyinstaller». Они предоставляют API или возможности для создания исполняемых файлов, которые могут выполняться в фоновом режиме. Эти инструменты требуют дополнительной настройки и установки, и вам может потребоваться ознакомиться с документацией их использования.

Надеюсь, эти способы помогут вам запустить Python скрипт в фоновом режиме на Windows! Если у вас возникнут дополнительные вопросы, не стесняйтесь задавать.

  • Python для системного администратора windows
  • Qaa неизвестный языковой стандарт windows 10 как убрать
  • Python setup failed windows 7 service pack 1
  • Python работа с реестром windows
  • Qbittorrent 64 bit rus скачать для windows 10