Michael R
Michael R

Reputation: 259

Running a python script in background with raw_input command

I have a python script that has a raw input command, but I would like to run it in the background after the user inputs the raw_input part. The problem I have is if I try running the script in the background using &, the raw input pops up as a linux command and the python script doesn't recognize it.

Any tips?

Upvotes: 2

Views: 1589

Answers (2)

miku
miku

Reputation: 188144

You can use fork to create a child process and then exit the parent.

#!/usr/bin/env python

import os
import sys
import time

_ = raw_input('Enter the the secret code: ')
if os.fork(): # returns 0 in the child, pid of the child in the parent
    sys.exit()

time.sleep(2)
print('All good things must come to an end')

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599926

You probably want to run the script in the foreground, but then call os.fork() after the user has input the value.

Upvotes: 1

Related Questions