击/ Python的:不`echo`命令插入输入代理到另一个命令时换行? [英] Bash/Python: does `echo` command insert a newline when acting as input to another command?

查看:123
本文介绍了击/ Python的:不`echo`命令插入输入代理到另一个命令时换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Python脚本 line_printer.py

I have a simple python script line_printer.py:

import fileinput
i = 1
for line in fileinput.input():
    print 'Line', str(i), ':', line.strip()
    i+=1

我想了解如何在管道数据来自回声命令这个脚本影响的结果与从文件中读取数据。

I'm trying to understand how piping data in from the echo command to this script affects the result versus reading the data in from file.

考虑下面的调用和输出:

Consider the following call and output:

$ echo -e "chicken\ncow\npig"
chicken
cow
pig
$

这对我看起来像回声已追加了invisble \\ n 猪的G之后。那么,如何来当我打电话:

This to me looks like echo has appended an invisble \n after the "g" in pig. So, how come when I call:

echo -e "chicken\ncow\npig" | python line_printer.py

我得到:

Line 1 : chicken
Line 2 : dog
Line 3 : cow

作为输出,而不是

as the output and not:

Line 1 : chicken
Line 2 : dog
Line 3 : cow
Line 4 : 

起初我还以为Python的的FileInput 模块的行为可能是放弃线下决赛的文件,如果它是空的。但是当我尝试使用一个文件 some_lines.txt 的内容:

At first I thought the behaviour of Python's fileinput module might be to discard the final line in a file if it is blank. But when I try using the contents of a file some_lines.txt:

chicken
dog
cow
<blank line>

作为输入:

python line_printer.py some_lines.txt

我得到的输出是:

The output I get is:

Line 1 : chicken
Line 2 : dog
Line 3 : cow
Line 4 : 

那么,为什么 line_printer.py 给上取决于它起源于标准输入与源自文件的输入不同的结果?最好的我可以说,这两个标准输入(从回声)和文件(从 some_lines.txt )完成了 \\ n ,所以我要么期望两者的输出包含 4号线:或既不包括输出吧。

So why does line_printer.py give different results on the input depending on whether it originated from stdin versus originated from a file? Best I can tell, both stdin (from echo) and the file (from some_lines.txt) finish with a \n, so I would either expect the output of both to include the Line 4 : or the output of neither to include it.

推荐答案

如果您在bash的来源看,庆典-4.2 /内建/ echo.def你可以看到内置的回声命令总是(行113)输出最终的 \\ n (行194),除非是 -n 指定(行198)或输出回声作为一个字符串(行166)。您可以通过测试该

If you look in the bash source, bash-4.2/builtins/echo.def you can see that the builtin echo command always (line 113) outputs a final \n (line 194) unless the -n was specified (line 198) or output of echo is used as a string (line 166). You can test this by doing

echo `echo "Ho ho ho"` | od -c

您会看到只有一个 \\ n ,因为回声嗬嗬嗬的输出作为评估字符串中的前pression 回声'回声嗬嗬嗬`

You will see only one \n because the output of echo "Ho ho ho" is evaluated as a string in the expression echo `echo "Ho ho ho"`.

这似乎没有任何关系到终端设置。

It doesn't seem to have any relation to the terminal setup.

这篇关于击/ Python的:不`echo`命令插入输入代理到另一个命令时换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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