- Bring the current Python program to background
- 2 Answers 2
- Running a Python Script in the Background
- Make Python Script Executable
- Start Python Script in Background
- Find and Kill the Running Process
- Output Buffering
- How To Run Python Script Constantly In Background
- 1. Using sched To Run Python Script Constantly In Background
- 2. Using the time.sleep() Function To Run Script repeatedly
- How To Run Python Script In Background In Linux
- How To Run Python Script In Background In Windows
- Wrap Up
Bring the current Python program to background
A python script prints information to screen and then should go to background. How to do that from within the script itself?
@tmg: That’s not a dup. The link you posted is how to start a new process in the background, not how to make the current process go to the background after some actions.
2 Answers 2
Copying related code from Creating a daemon the Python way; please read the comments as to why that code is quite thought-out.
def createDaemon(): """Detach a process from the controlling terminal and run it in the background as a daemon. """ try: # Fork a child process so the parent can exit. This returns control to # the command-line or shell. It also guarantees that the child will not # be a process group leader, since the child receives a new process ID # and inherits the parent's process group ID. This step is required # to insure that the next call to os.setsid is successful. pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The first child. # To become the session leader of this new session and the process group # leader of the new process group, we call os.setsid(). The process is # also guaranteed not to have a controlling terminal. os.setsid() # Is ignoring SIGHUP necessary? # # It's often suggested that the SIGHUP signal should be ignored before # the second fork to avoid premature termination of the process. The # reason is that when the first child terminates, all processes, e.g. # the second child, in the orphaned group will be sent a SIGHUP. # # "However, as part of the session management system, there are exactly # two cases where SIGHUP is sent on the death of a process: # # 1) When the process that dies is the session leader of a session that # is attached to a terminal device, SIGHUP is sent to all processes # in the foreground process group of that terminal device. # 2) When the death of a process causes a process group to become # orphaned, and one or more processes in the orphaned group are # stopped, then SIGHUP and SIGCONT are sent to all members of the # orphaned group." [2] # # The first case can be ignored since the child is guaranteed not to have # a controlling terminal. The second case isn't so easy to dismiss. # The process group is orphaned when the first child terminates and # POSIX.1 requires that every STOPPED process in an orphaned process # group be sent a SIGHUP signal followed by a SIGCONT signal. Since the # second child is not STOPPED though, we can safely forego ignoring the # SIGHUP signal. In any case, there are no ill-effects if it is ignored. # # import signal # Set handlers for asynchronous events. # signal.signal(signal.SIGHUP, signal.SIG_IGN) try: # Fork a second child and exit immediately to prevent zombies. This # causes the second child process to be orphaned, making the init # process responsible for its cleanup. And, since the first child is # a session leader without a controlling terminal, it's possible for # it to acquire one by opening a terminal in the future (System V- # based systems). This second fork guarantees that the child is no # longer a session leader, preventing the daemon from ever acquiring # a controlling terminal. pid = os.fork() # Fork a second child. except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The second child. # Since the current working directory may be a mounted filesystem, we # avoid the issue of not being able to unmount the filesystem at # shutdown time by changing it to the root directory. os.chdir(WORKDIR) # We probably don't want the file mode creation mask inherited from # the parent, so we give the child complete control over permissions. os.umask(UMASK) else: # exit() or _exit()? See below. os._exit(0) # Exit parent (the first child) of the second child. else: # exit() or _exit()? # _exit is like exit(), but it doesn't call any functions registered # with atexit (and on_exit) or any registered signal handlers. It also # closes any open file descriptors. Using exit() may cause all stdio # streams to be flushed twice and any temporary files may be unexpectedly # removed. It's therefore recommended that child branches of a fork() # and the parent branch(es) of a daemon use _exit(). os._exit(0) # Exit parent of the first child.
Running a Python Script in the Background
This is a quick little guide on how to run a Python script in the background in Linux.
Make Python Script Executable
First, you need to add a shebang line in the Python script which looks like the following:
This path is necessary if you have multiple versions of Python installed and /usr/bin/env will ensure that the first Python interpreter in your $PATH environment variable is taken. You can also hardcode the path of your Python interpreter (e.g. #!/usr/bin/python3 ), but this is not flexible and not portable on other machines. Next, you’ll need to set the permissions of the file to allow execution:
Start Python Script in Background
Now you can run the script with nohup which ignores the hangup signal. This means that you can close the terminal without stopping the execution. Also, don’t forget to add & so the script runs in the background:
If you did not add a shebang to the file you can instead run the script with this command:
nohup python /path/to/test.py &
The output will be saved in the nohup.out file, unless you specify the output file like here:
nohup /path/to/test.py > output.log & nohup python /path/to/test.py > output.log &
Find and Kill the Running Process
You can find the process and its process Id with this command:
If you want to stop the execution, you can kill it with the kill command:
It is also possible to kill the process by using pkill, but make sure you check if there is not a different script running with the same name:
Output Buffering
If you check the output file nohup.out during execution you might notice that the outputs are not written into this file until the execution is finished. This happens because of output buffering. If you add the -u flag you can avoid output buffering like this:
Or by specifying a log file:
nohup python -u ./test.py > output.log &
How To Run Python Script Constantly In Background
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.
1. Using sched To 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()
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)
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.
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.
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.