Move python code to background after running part of it

I have python code that has some part that needs to be run in the foreground, as it reports that the socket connection was correct or not. Now after starting this part, the output is written to a file.

Is there a way to move the executable code (process) in Python automatically from the foreground to the background after following certain steps in the foreground so that I can continue to work on the terminal.

I know use screenis an option, but is there any other way to do this. Since after starting the part in the foreground there will be no output displayed on the terminal, I do not want to launch the screen unnecessarily.

+4
source share
2 answers

In python, you can disconnect from the current terminal by noticing that this will only work on UNIX-like systems:

# Foreground stuff
value = raw_input("Please enter a value: ")

import os

pid = os.fork()
if pid == 0:
    # Child
    os.setsid()  # This creates a new session
    print "In background:", os.getpid()

    # Fun stuff to run in background

else:
    # Parent
    print "In foreground:", os.getpid()
    exit()

In Bash, you really can only do things interactively. If you want to put the python process in the background, use CTRL + Z (the lead $is a symbol for the general Bash hint):

$ python gash.py
Please enter a value: jjj
^Z
[1]+  Stopped                 python gash.py
$ bg
[1]+ python gash.py &
$ jobs
[1]+  Running                 python gash.py &

Note that using setsid()python in the code will not show the process in jobs, since the background job is controlled by the shell, not python.

+4
source

If you have #! / Bin / env python and its permissions are set correctly, you can try something like nohup /path/to/test.py &

+1
source

All Articles