问题
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?>
}
回答1:
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
}
回答2:
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
来源:https://stackoverflow.com/questions/34829145/a-bash-function-that-runs-script