Search code examples
pythonbackgroundraw-input

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?


Solution

  • 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')