运行scrip的bash函数

2024-04-25 23:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个名为myrun的bash函数,这样做

myrun script.py

使用Python文件:

#MYRUN:nohup python -u script.py &

import time
print 'Hello world'
time.sleep(2)
print 'Once again'

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

{strong}我应该插入什么?这是我现在拥有的:

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

Tags: 文件函数pyimportbashhelloworldtime
2条回答

这与Bash无关。不幸的是,shebang行不能包含多个参数或选项组。你知道吗

如果您的目标是为Python指定选项,那么最简单的可能就是一个简单的sh包装器:

#!/bin/sh
nohup python -u <<'____HERE' &
.... Your Python script here ...
____HERE

极简主义版本:

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

相关问题 更多 >