A bash function that runs script

筅森魡賤 提交于 2019-12-08 02:43:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!