在bash脚本中embedded短python脚本

我想embedded一个bash脚本内的短python脚本的文本,用于说,我的.bash_profile 。 什么是最好的方式去做这样的事情?

我到目前为止的解决scheme是使用-c选项调用python解释器,并告诉解释器exec它从stdin读取的内容。 从那里,我可以构build如下所示的简单工具,使我可以在交互式提示中处理文本:

 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)] % " 

这个方法虽然对我来说有些奇怪,但我想知道以这种方式做什么替代方法可能会是。

我的bash脚本编写技巧是相当简单的,所以我特别感兴趣的是,如果我从bash解释器的angular度来看是否做了些傻事。

Python解释器接受-在命令行中作为stdin的同义词,所以你可以用pyexecreplace掉调用:

 python - <<END 

请参阅此处的命令行参考。

为什么你需要使用-c ? 这适用于我:

 python << END ... code ... END 

无需任何额外的东西。

如果你需要在bash脚本中使用python的输出,你可以这样做:

 #!/bin/bash ASDF="it didn't work" ASDF=`python <<END ASDF = 'it worked' print ASDF END` echo $ASDF 

有时使用这里的文档不是一个好主意。 另一种select是使用python -c:

 py_script=" import xml.etree.cElementTree as ET,sys ... " python -c "$py_script" arg1 arg2 ... 

here document使用bash here document一个问题是,脚本然后传递到Python的stdin ,所以如果你想使用Python脚本作为filter,它变得笨拙。 另一种方法是使用bashprocess substitution ,如下所示:

 ... | python <( echo ' code here ' ) | ... 

如果脚本太长,你也可以here document使用paren here document ,像这样:

 ... | python <( cat << END code here END ) | ... 

在脚本内部,您可以像往常一样从/读取/写入标准I / O(例如, sys.stdin.readlines来吞噬所有input)。

另外, python -c可以像其他答案中提到的那样使用,但是我仍然喜欢在Python中使用缩进规则( 信用 ):

 read -r -d '' script <<-"EOF" code goes here prefixed by hard tab EOF python -c $script 

只要确保在这里的每一行文字的第一个字符是一个硬标签。 如果你必须把它放在一个函数中,那么我使用下面的技巧来看看它是否alignment:

 function somefunc() { read -r -d '' script <<-"----EOF" code goes here prefixed by hard tab ----EOF python -c $script } 

有趣…我现在也想回答;-)

他不问如何在bash脚本中执行python代码,但实际上有python设置环境variables。

把它放在一个bash脚本中,试着让它说“它工作”。

 export ASDF="it didn't work" python <<END import os os.environ['ASDF'] = 'it worked' END echo $ASDF 

问题是python被执行在一个环境的副本。 python退出后,没有看到对该环境的任何更改。

如果有解决scheme,我也很想看到它。

准备复制粘贴示例:

 input="hello" output=`python <<END print $input+" world"; END` echo $output 

如果您使用zsh,您可以使用zsh的连接和python stdin选项( python - )将脚本embedded到脚本中:

 py_cmd=${(j:\n:)"${(f)$( # You can also add comments, as long as you balance quotes <<<'if var == "quoted text":' <<<' print "great!"')}"} catch_output=$(echo $py_cmd | python -) 

您可以缩进Python代码片段,因此在内部函数中它看起来比EOF<<END解决scheme更好。

尝试这个 :

 #!/bin/bash a="test" python -c "print '$a this is a test'.title()"