5

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.

4
  • Which operating-system and shell? Commented Jun 8, 2015 at 13:17
  • Ubuntu 14.04LTS and bash Commented Jun 8, 2015 at 13:18
  • Do you wish to do this in the python or from bash? Commented Jun 8, 2015 at 13:20
  • preferably python, but if not possible in python then bash. If it is possible in both, please write method for both. Commented Jun 8, 2015 at 13:21

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

But won't this run the program in the background from start?
Oh right. Can you not just Ctrl-Z the process, then restart in in the background with bg? Also, if you want to bring it to the foreground then you can use fg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.