I'm trying to write a bash function named myrun, such that doing
myrun script.py
with a Python file:
#MYRUN:nohup python -u script.py &
import time
print 'Hello world'
time.sleep(2)
print 'Once again'
will run the script with the command specified in the first line of the file, just after #MYRUN:.
What should I insert in .bashrc to allow this? Here is what I have now:
myrun () {
[[ "1ドル" = "" ]] && echo "usage: myrun python_script.py" && return 0
<something with awk here or something else?>
}
2 Answers 2
A minimalist version:
$ function myrun {
[[ "1ドル" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 1 < "1ドル" | sed s'/# *MYRUN://')
$cmd
}
$ myrun script.py
appending output to nohup.out
$ cat nohup.out
Hello world
Once again
$
(It's not clear to me whether you're better off using eval "$cmd" or simply $cmd in the last line of the function, but if you want to include the "&" in the MYCMD directive, then $cmd is simpler.)
With some basic checking:
function myrun {
[[ "1ドル" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 1 <"1ドル")
if [[ $cmd =~ ^#MYRUN: ]] ; then cmd=${cmd#'#MYRUN:'}
else echo "myrun: #MYRUN: header not found" >&2 ; false; return ; fi
if [[ -z $cmd ]] ; then echo "myrun: no command specified" >&2 ; false; return; fi
$cmd # or eval "$cmd" if you prefer
}
3 Comments
#MYRUN: is not found... Currently it would try to run the first line anyway!eval "$cmd" rather than just $cmd (which has totally different rules for how the command is parsed).eval approach will always be more desirable. See BashFAQ #50 -- mywiki.wooledge.org/BashFAQ/050 -- for a discussion of the pitfalls in the other approach (quotes are treated as literal data, spaces can't possibly be escaped, etc).This is unrelated to Bash. Unfortunately, the shebang line cannot portably contain more than a single argument or option group.
If your goal is to specify options to Python, the simplest thing is probably a simple sh wrapper:
#!/bin/sh
nohup python -u <<'____HERE' &
.... Your Python script here ...
____HERE
1 Comment
nohup's work in native Python; it's not that hard to reopen the standard FD set and set signal-handling behavior for HUP.
myrun script.py.--no-forkon the command line, you could do:subprocess.Popen(['nohup', sys.executable, sys.argv[0], '--no-fork'] + sys.argv[1:]); exit(). (I'd advise you check that--no-forkworks before following this example though, or you'll end up with a process that keeps spawning then dying).