bash scrip中从stdin到python代码的管道

2024-06-17 14:48:17 发布

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

我有一个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
EOPYTHON

我试着把上面代码中的第二行改成下面的,但没有成功

python << EOPYTHON $*

我不知道该怎么做。有什么建议吗?

编辑 我将举一个更具体的例子。考虑下面的bash脚本,f

#!/bin/bash
python << EOPYTHON 
import sys
import fileinput
for i in fileinput.input():
    sys.stdout.write(i + '\n')
EOPYTHON

我想用下面的命令运行我的代码

f input.txt > output.txt

如何更改bash脚本,使其使用“input.txt”作为输入流?


Tags: 文件代码importtxt脚本bash示例input
3条回答

由于没有人提到这一点,以下是作者的要求。神奇的是将“-”作为参数传递给cpython(从stdin读取源代码的指令):

输出到文件:

python - << EOF > out.txt
print("hello")
EOF

执行示例:

# python - << EOF
> print("hello")
> EOF
hello

由于数据无法再通过stdin传递,这里还有一个技巧:

data=`cat input.txt`

python - <<EOF

data="""${data}"""
print(data)

EOF

更新答案

如果你一定要按你的要求去做,你可以这样做:

#!/bin/bash
python -c 'import os
for i in range(3):
   for j in range(3):
     print(i + j)
'  < "$1"

原始答案

将python代码保存在名为script.py的文件中,并将脚本f更改为:

#!/bin/bash
python script.py < "$1"

您只需对照进程的文件描述符列表检查它,即在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

相关问题 更多 >