Basj
Basj

Reputation: 46463

Shebang to start a Python script with nohup

I find it quite long to have to write:

nohup python -u myscript.py > log.txt 2>&1 &

each time I want to launch a Python script as a background process.

Is it possible to have a shebang-like first line of script like:

#!nohup python -u myscript.py > log.txt 2>&1 &
import time
while True:
    print 'hello'
    time.sleep(1)

such that a command like

run myscript.py

would automatically start the script with the command present in the first line of myscript.py?

Note: I'm looking for a single-file solution, I don't want to have to have a second file myscript.sh bash script along myscript.py to do this job.

Upvotes: 3

Views: 1415

Answers (3)

andreas-hofmann
andreas-hofmann

Reputation: 2518

As mentioned in the comment above, you could try to use os.fork() to send your script to background. As for stdout/stderr redirection, you can additionally overwrite the filehandles to achieve the desired result. Look at this example:

import os
import sys

class LogWriter(object):
    def __init__(self, logfile):
        self._f = open(logfile, "w")

    def write(self, data):
        self._f.write(data)
        self._f.flush()

logger = LogWriter("test.log")
sys.stdout = logger
sys.stderr = logger

if os.fork():
    sys.exit()

# Main loop
import time
while True:
    print 'hello'
    time.sleep(1)

The class LogWriter is introduced to add a flush() to every write, which occurs. The forked process remains running, if you close the ssh session which started the script.

Upvotes: 0

Ayush
Ayush

Reputation: 3935

well, this one writes to nohup.out instead of a custom file. And afaik, suspending to background using a shebang hack is not possible

#!/usr/bin/nohup python

import sys

print("to stdout")
print("to stderr",file=sys.stderr)

Giving arguments to shebang interpreter (Berkeley exec hack) does not support any form of io redirection, so your best bet might be to use a custom script as decribed in gilhad's answer

Upvotes: 0

gilhad
gilhad

Reputation: 609

I am afraid, that it is not directly possible, but you can overcome it like this:

create file run_py.sh somewhere (maybe in /home/basj/bin/ ) and make it runable:

#!/bin/bash
nohup python -u "$@" > log.txt 2>&1 &

then include in your python files this header (and make them runable)

#!/home/basj/bin/run_py.sh
print "I am in python on background with nohup now :)"

Upvotes: 1

Related Questions