嵌入bash脚本里短的Python脚本 [英] embedding short python scripts inside a bash script
问题描述
我想嵌入短的Python脚本的文本的bash脚本内,用于在说,我的的.bash_profile
。什么是去这样做这样的事情的最好方法?
I'd like to embed the text of short python scripts inside of a bash script, for use in say, my .bash_profile
. What's the best way to go about doing such a thing?
解决方案我到目前为止是调用蟒蛇间preTER与 -c
选项,并告诉间preTER到 EXEC
标准输入。从那里,我可以建立简单的工具,如下面,让我来处理使用文字在我的交互提示:
The solution I have so far is to call the python interpreter with the -c
option, and tell the interpreter to exec
whatever it reads from stdin
. From there, I can build simple tools like the following, allowing me to process text for use in my interactive prompt:
function pyexec() {
echo "$(/usr/bin/python -c 'import sys; exec sys.stdin.read()')"
}
function traildirs() {
pyexec <<END
trail=int('${1:-3}')
import os
home = os.path.abspath(os.environ['HOME'])
cwd = os.environ['PWD']
if cwd.startswith(home):
cwd = cwd.replace(home, '~', 1)
parts = cwd.split('/')
joined = os.path.join(*parts[-trail:])
if len(parts) <= trail and not joined.startswith('~'):
joined = '/'+joined
print joined
END
}
export PS1="\h [\$(traildirs 2)] % "
此方法略有气味好笑我虽然,我想知道这种方式可能是什么替代这样做。
This approach smells slightly funny to me though, and I'm wondering what alternatives to doing it this way might be.
我的bash脚本编程技能是pretty简陋,所以我听到的话,我做的东西从bash的跨preTER的角度看傻了特别感兴趣。
My bash scripting skills are pretty rudimentary, so I'm particularly interested to hear if I'm doing something silly from the bash interpreter's perspective.
推荐答案
蟒蛇间preTER接受 -
命令行的同义词关于标准输入
这样你就可以取代电话一起pyexec:
The python interpreter accepts -
on the command line as a synonym for stdin
so you can replace the calls to pyexec with:
python - <<END
请参阅命令行参考这里。
这篇关于嵌入bash脚本里短的Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!