Move python code to background after running a part of it

3k views Asked by At

I have a python code, which has some part that needs to be run on foreground since it tells out if the socket connection was proper or not. Now after running that part the output is written into a file.

Is there a way to move the running python code (process) automatically from foreground to background after running some definite steps in foreground, so that I can continue my work on terminal.

I know using screen is a option but is there any other way to do so. Since after running a part on foreground, there won't be any output shown in the terminal, I don't want to run screen unnecessarily.

2

There are 2 answers

0
cdarke On BEST ANSWER

In python, you can detach from the current terminal, note 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 can really only do things interactively. When you wish to place the python process into background use CTRL+Z (the leading $ is the convention for a generic bash prompt):

$ 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() in the python code will not show the process in jobs, since background job management is done by the shell, not by python.

2
Jeremy On

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