A bash function that runs script

社会主义新天地 提交于 2019-12-06 13:17:51

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
}

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