Skip to main content
 首页 » 编程设计

python之运行脚本的 bash 函数

2024年10月24日14freeliver54

我正在尝试编写一个名为 myrun 的 bash 函数,以便执行

myrun script.py 

使用 Python 文件:

#MYRUN:nohup python -u script.py & 
 
import time 
print 'Hello world' 
time.sleep(2) 
print 'Once again' 

将使用文件第一行中指定的命令运行脚本,就在#MYRUN:之后。

我应该在 .bashrc 中插入什么以允许这样做?这是我现在拥有的:

myrun () { 
[[ "$1" = "" ]] && echo "usage: myrun python_script.py" && return 0 
<something with awk here or something else?> 
} 

请您参考如下方法:

极简版:

$ 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  
$ 

(我不清楚在函数的最后一行使用 eval "$cmd" 还是简单地使用 $cmd 更好,但是如果你想在 MYCMD 指令中包含“&”,那么 $cmd 更简单。)

通过一些基本检查:

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 
}