运行脚本的 bash 函数
A bash function that runs script
我正在尝试编写一个名为 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 () {
[[ "" = "" ]] && echo "usage: myrun python_script.py" && return 0
<something with awk here or something else?>
}
这与 Bash 无关。不幸的是,shebang 行不能移植地包含多个参数或选项组。
如果您的目标是为 Python 指定选项,最简单的可能是一个简单的 sh
包装器:
#!/bin/sh
nohup python -u <<'____HERE' &
.... Your Python script here ...
____HERE
极简版:
$ function myrun {
[[ "" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 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 {
[[ "" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 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
}
我正在尝试编写一个名为 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 () {
[[ "" = "" ]] && echo "usage: myrun python_script.py" && return 0
<something with awk here or something else?>
}
这与 Bash 无关。不幸的是,shebang 行不能移植地包含多个参数或选项组。
如果您的目标是为 Python 指定选项,最简单的可能是一个简单的 sh
包装器:
#!/bin/sh
nohup python -u <<'____HERE' &
.... Your Python script here ...
____HERE
极简版:
$ function myrun {
[[ "" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 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 {
[[ "" = "" ]] && echo "usage: myrun python_script.py" && return
local cmd=$(head -n 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
}