Is it possible for me to run a Python Script so that it firsts runs and prompts for the different inputs it needs, then goes out into the background and runs but frees up my terminal?
1 Answer
Yes, launch your script, and when you're done, use Ctrl+Z to pause it. Once paused, running bg
will send it to the background where it will continue running. For example:
$ myscript.py
Enter a number: 2
^Z
[1]+ Stopped myscript.py
$ bg
[1]+ myscript.py &
The ^Z
is when I pressed Ctrl+Z. Now, if you want to bring the script back to the foreground, run fg
.
If you want to do this for multiple scripts, you can use jobs
to list backgrounded jobs:
$ jobs
[1]- Running myscript1.py
[2]+ Running myscript2.py
The numbers in the brackets are the job ids. To bring a specific one back to the foreground, use its ID:
jobs 2
The command above will bring the second one. Use 1
for the first, 3
for the third and so on.
-
Works great, thank you! My only question now is, how does bg and fg know which script to send to background or bring to foreground? If I am running multiple scripts, how should I manage them so that I can choose which to send to background or bring to foreground?– RohanOct 1, 2015 at 0:39
-
-
Cool! And one last thing. If my program runs into an error while in background, how will I find out about it, especially when it happens while I am not logged into any user? Will I get an error report when I log in?– RohanOct 1, 2015 at 1:42
-
Speaking of which, what happens after I log off? I tried it out, and when I log back in, I can't see it in jobs, but I can see it through ps aux | grep python. So how can I still manage them? That should be my last question– RohanOct 1, 2015 at 1:49
-
@Rohan if you log out, you're on your own. On some systems, the script will be killed when you log out, on others not, but I don't think it's possible to get it back. You'll have to let it finish or kill it. If you need to do something like that, you'll have to use something like
screen
ortmux
.– terdonOct 3, 2015 at 11:02