在bash脚本中从stdin传递到python代码 [英] piping from stdin to a python code in a bash script

查看:57
本文介绍了在bash脚本中从stdin传递到python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本f,其中包含python代码.该python代码从标准输入中读取.我希望能够按以下方式调用我的bash脚本:

I have a bash script, f, that contains python code. That python code reads from standard input. I want to be able to call my bash script as follows:

f input.txt > output.txt

在上面的示例中,python代码将从input.txt中读取,并将写入output.txt.

In the example above, the python code will read from input.txt and will write to output.txt.

我不确定该怎么做.我知道,如果我只想写入文件,那么我的bash脚本将如下所示:

I'm not sure how to do this. I know that if I wanted to just write to a file, then my bash script would look like this

#!/bin/bash
python << EOPYTHON > output.txt
#python code goes here
EOPYTHON

我尝试将上面代码中的第二行更改为以下内容,但是没有运气

I tried changing the second line in the code above to the following, but without luck

python << EOPYTHON $*

我不确定该怎么做.有什么建议吗?

I'm not sure how else to go about doing this. Any suggestions?

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

EDIT I'll give a more concrete example. Consider the following bash script, f

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

我想使用以下命令运行代码

I want to run my code with the following command

f input.txt > output.txt

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

How do I change my bash script so that it uses "input.txt" as the input stream?

推荐答案

更新后的答案

如果您绝对必须按照自己的方式行事,则可以执行以下操作:

If you absolutely must run the way you ask, you could do something like this:

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

原始答案

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

Save your python code in a file called script.py and change your script f to this:

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

这篇关于在bash脚本中从stdin传递到python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆