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

Author:
Ahmedur Rahman Shovon

Scenario

Suppose, we have a Python script that uses some Python packages.
To keep the global environment clean, we use a virtual environment (venv) to install the dependencies.
Let’s assume, the script requires a long time to finish.
We may need to check the intermediate results (e.g. print statement debugging) from the script during the execution process.
We also want to run the script in the background without blocking a terminal window.

I will mock this scenario and will show how to run the Python script inside a virtual environment in the background that writes partial output to a file.

Running script in the foreground

  • Create and activate virtual environment using Python 3:

    python3 -m venv venv
    source venv/bin/activate
    
  • Suppose the required packages are listed in requirements.txt:

    numpy==1.22.3
    
  • Install the required packages:

    pip install -r requirements.txt
    
  • Create a Python script that generates 3 random integers and sleep for 5 seconds at each step. It continues the process until 30 integers are generated. The code is listed in background_script.py file:

    import time
    from datetime import datetime
    import numpy as np
        
    count = 0
    while True:
        current_time = datetime.now()
        rng = np.random.default_rng()
        random_integers = rng.integers(low=0, high=10 ** 6, size=3)
        print(f"{current_time}: {random_integers}")
        count += 1
        if count == 10:
            print(f"Script completed")
            break
        time.sleep(5)
    
  • Run the Python script (background_script.py):

    python background_script.py
    
  • It shows 3 random numbers continuously each 5 seconds.
    The script takes 50 seconds to complete and will stop after printing 30 random numbers:

    2022-03-18 04:18:12.376506: [874273 493185 580873]
    2022-03-18 04:18:17.378234: [175390 989369 463402]
    2022-03-18 04:18:22.382138: [721299 669516 197204]
    2022-03-18 04:18:27.386138: [537835 627442 400862]
    ...
    ...
    Script completed
    

Running script using Bash in the background

  • Let’s create a Shell script (run_bg.sh) in the same directory that activates the virtual environment and runs the Python script. We have used -u parameter in the Python run command that enables printing the partial outputs to the standard output:

    #!/usr/bin/env bash
    set -e
    source "./venv/bin/activate"
    python -u background_script.py
    
  • Run the script in the foreground to check if it can activate the virtual environment and runs the Python script:

    ./run_bg.sh
    
  • If the above Shell script runs without error, we try to run it in a background process using nohup command. This will write the partial outputs to a file (custom-output.log):

    nohup ./run_bg.sh > custom-output.log &
    
  • We can see the partial output using:

    cat custom-output.log
    

    alt Run Python Script in background with partial output

  • Sometimes we may need to stop the script running in the background. We need to kill the process which runs the script to do so. The following command will list the process ID for the script:

    ps aux | grep background_script.py
    

    It will return the process details which contain the process ID, typically in the second column.
    Then we can kill the process by using:

    kill PROCESS_ID
    

Use case

I was trying to run a hefty Python script that requires a virtual environment in a cluster computing platform.
I did not want to keep the terminal session open as the script would take days to finish.
I also wanted to see the partial output while the script was running.

So, I followed this approach to run the Python script inside a virtual environment in the background that wrote the partial output to a file.

References

  • sh command man page
  • nohup(1) — Linux manual page
Cite This Work
APA Style
Shovon, A. R.
(2022, March 18).
Run a Python script inside a virtual environment in the background.
Ahmedur Rahman Shovon.
Retrieved September 23, 2023, from
https://arshovon.com/blog/python-background/
MLA Style
Shovon, Ahmedur Rahman.
“Run a Python script inside a virtual environment in the background.”
Ahmedur Rahman Shovon,
18 Mar. 2022.
Web.
23 Sep. 2023.
https://arshovon.com/blog/python-background/.
BibTeX entry
@misc{ shovon_2022,
    author = "Shovon, Ahmedur Rahman",
    title = "Run a Python script inside a virtual environment in the background",
    year = "2022",
    url = "https://arshovon.com/blog/python-background/",
    note = "[Online; accessed 23-September-2023; URL: https://arshovon.com/blog/python-background/]"
}
Related Contents in this Website

Сценарий мониторинга test1.py, написанный на python, работает в режиме True. Когда ssh удален (с помощью терминала замазки), запустите сценарий с помощью следующей команды:

python test1.py &

Теперь сценарий работает нормально, вы можете увидеть номер процесса через ps, в это время непосредственно закройте терминал ssh (не используя команду выхода, но непосредственно через кнопку закрытия putty), после входа в систему снова и найденный Процесс уже завершен.

Проблема была решена путем запуска в фоновом режиме, и ее можно суммировать здесь, чтобы я мог обратиться к ней позже.

бегать в фоновом режиме под окнами

Под окнами нет глубоких исследований. Метод, который я часто использую, заключается в изменении расширения скрипта Python «.pyw». Двойной щелчок запускается в фоновом режиме без изменения кода.

Запустите в фоновом режиме под Linux

Через вилку
В среде Linux процесс демона в c реализован с помощью fork, и python также может быть реализован таким образом. Пример кода следующий:

#!/usr/bin/env python
import time,platform
import os
def funzioneDemo():
    # Это пример конкретной бизнес-функции
    fout = open('/tmp/demone.log', 'w')
    while True:
        fout.write(time.ctime()+'\n')
        fout.flush()
        time.sleep(2)
    fout.close()
def createDaemon():
         # форк процесс        
    try:
        if os.fork() > 0: os._exit(0)
    except OSError, error:
        print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)
        os._exit(1)    
    os.chdir('/')
    os.setsid()
    os.umask(0)
    try:
        pid = os.fork()
        if pid > 0:
            print 'Daemon PID %d' % pid
            os._exit(0)
    except OSError, error:
        print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)
        os._exit(1)
         # Перенаправить стандартный IO
    sys.stdout.flush()
    sys.stderr.flush()
    si = file("/dev/null", 'r')
    so = file("/dev/null", 'a+')
    se = file("/dev/null", 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())
         # Выполнить код в дочернем процессе
    funzioneDemo() # function demo
if __name__ == '__main__': 
    if platform.system() == "Linux":
        createDaemon()
    else:
        os._exit(0)

Через выскочку

Приложение может быть упаковано как системная служба через upstart, и полный пример прямо записан здесь.

1. Напишите скрипт на Python

[root@local t27]# cat test123.py
#!/usr/bin/env python
import os,time
while True :
    print time.time()
    time.sleep(1)

2. Напишите файл конфигурации upstat

[root@local t27]# cat /etc/init/mikeTest.conf
description "My test"
author "[email protected]"
start on runlevel [234]
stop on runlevel [0156]
chdir /test/t27
exec /test/t27/test123.py
respawn
  • 3. Перезагрузить северную часть штата
initctl reload-configuration
  • 4. Запустите сервис
[root@local t27]# start mikeTest
mikeTest start/running, process 6635
[root@local t27]# ps aux | grep test123.py
root      6635  0.0  0.0  22448  3716 ?        Ss   09:55   0:00 python /test/t27/test123.py
root      6677  0.0  0.0 103212   752 pts/1    S+   09:56   0:00 grep test123.py
  • 5. Стоп сервис
[root@local t27]# stop mikeTest
mikeTest stop/waiting
[root@local t27]# ps aux | grep test123.py
root      6696  0.0  0.0 103212   752 pts/1    S+   09:56   0:00 grep test123.py
[root@local t27]#
  •  

Скрипт bash

1. код Python

[root@local test]# cat test123.py
#!/usr/bin/env python
import os,time
while True :
    print time.time()
    time.sleep(1)
  • 2. Написать скрипт запуска
[root@local test]# cat start.sh
#! /bin/sh
python test123.py &
  • 3. Запустите процесс
[root@local test]#./start.sh
  •  

Если вы используете & для запуска процесса напрямую:

python test123.py &
  •  

Непосредственное закрытие терминала ssh приведет к завершению процесса.

Через экран, tmux и т. Д.

Если вы временно запустите программу, вы можете запустить программу через screen, tmux, здесь описывается, как запускается tmux.

1. Запустите tmux

Введите tmux в терминал, чтобы начать

2. Запустите программу в tmux

Просто выполните следующую команду напрямую (ссылка на скрипт выше): python test123.py

3. Закройте терминал ssh напрямую (например, кнопку закрытия на замазке);

4. После перезапуска ssh выполните следующую команду:

tmux attach
  • Теперь вы можете видеть, что программа на python все еще работает нормально.

  • Qbittorrent клиент для windows 10
  • Python скачать для windows 7 sp1
  • Qbittorrent x64 на русском для windows 10 официальный сайт
  • Python какая версия поддерживает windows 7
  • Python скачать для windows 10 64 bit торрент