在bash脚本中从stdin到python代码的管道
我有一个bash脚本f,它包含python代码。python代码读取标准输入。我希望能够按如下方式调用我的bash脚本:在bash脚本中从stdin到python代码的管道,python,bash,Python,Bash,我有一个bash脚本f,它包含python代码。python代码读取标准输入。我希望能够按如下方式调用我的bash脚本: f input.txt > output.txt 在上面的示例中,python代码将从input.txt读取并写入output.txt 我不知道该怎么做。我知道,如果我只想写入一个文件,那么我的bash脚本将如下所示 #!/bin/bash python << EOPYTHON > output.txt #python code goes here
f input.txt > output.txt
在上面的示例中,python代码将从input.txt读取并写入output.txt
我不知道该怎么做。我知道,如果我只想写入一个文件,那么我的bash脚本将如下所示
#!/bin/bash
python << EOPYTHON > output.txt
#python code goes here
EOPYTHON
如何更改bash脚本,使其使用“input.txt”作为输入流?您只需对照进程的文件描述符列表检查它,即在proc文件系统上,您可以使用
readlink /proc/$$/fd/1
比如说
> cat test.sh
#!/bin/bash
readlink /proc/$$/fd/1
> ./test.sh
/dev/pts/3
> ./test.sh > out.txt
> cat out.txt
/home/out.txt
更新的答案 如果你必须按照你要求的方式运行,你可以这样做:
#!/bin/bash
python -c 'import os
for i in range(3):
for j in range(3):
print(i + j)
' < "$1"
-c
中的选项应该有效
这里有一个备选方案,您可以在Python脚本中嵌入bash
:
#!/usr/bin/env python
import sys
import fileinput
from subprocess import call
# shell command before the python code
rc = call(r"""
some bash-specific commands here
...
""", shell=True, executable='/bin/bash')
for line in fileinput.input():
sys.stdout.write(line) #NOTE: `line` already has a newline
# shell command after the python code
rc = call(r"""
some /bin/sh commands here
...
""", shell=True)
由于没有人提到这一点,以下是作者的要求。神奇的是将“-”作为参数传递给cpython(从stdin读取源代码的指令): 输出到文件时:
python - << EOF > out.txt
print("hello")
EOF
python-out.txt
打印(“你好”)
EOF
执行示例:
# python - << EOF
> print("hello")
> EOF
hello
#python-print(“你好”)
>EOF
你好
由于数据不能再通过stdin传递,下面是另一个技巧:
data=`cat input.txt`
python - <<EOF
data="""${data}"""
print(data)
EOF
data=`cat input.txt`
python-ffoutput.txt
有什么问题?“我有一个bash脚本f,它包含python代码。”为什么?如果每个源文件只使用一种语言,您可能会发现代码更容易维护。因此,我将解释这个问题,因为您希望知道在脚本中直接将python输出重定向到何处(即,该脚本被称为redirecting stoudt to output.txt)。我的回答应该可以解决这个问题,但还是有点奇怪,为什么不能将python打印到标准输出,让bash处理脚本外部的重定向?@Johnsyweb你从来没有为用另一种语言编写的脚本制作过包装器?@BroSlow:当然有,但包装器可以调用外部文件,而不是包含它。这种关注点的分离促进了可测试性和可维护性。我想要一个不在目录中保存另一个文件的解决方案。请再看一看-我已经更新为在单引号包围时使用Bash的多行输入。+1;将-c
与Python源代码字符串一起使用确实是关键:它允许将stdin输入传递给Python代码(而不是像
#!/usr/bin/env python
import sys
import fileinput
from subprocess import call
# shell command before the python code
rc = call(r"""
some bash-specific commands here
...
""", shell=True, executable='/bin/bash')
for line in fileinput.input():
sys.stdout.write(line) #NOTE: `line` already has a newline
# shell command after the python code
rc = call(r"""
some /bin/sh commands here
...
""", shell=True)
python - << EOF > out.txt
print("hello")
EOF
# python - << EOF
> print("hello")
> EOF
hello
data=`cat input.txt`
python - <<EOF
data="""${data}"""
print(data)
EOF