简体   繁体   English

python打印输出通过管道传输到BASH导致“管道中断”

[英]python print output piped to BASH leads to “broken pipe”

I have a python script that prints to the stdout a list of files, for example: 我有一个python脚本,可以向标准输出打印文件列表,例如:

$ ./myscript.py "file a.txt" "file b.txt" "file c.txt"

I want to open these files in LESS 我想在LESS中打开这些文件

$ less <(./myscript.py)

But I get the following error: 但是我收到以下错误:

-bash: /dev/fd/63: Permission denied $ Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> BrokenPipeError: [Errno 32] Broken pipe

I think it may be the same problem as @Jon-Clements refers to in grep: broken pipe error python 2.2 , ie the pipe is finished; 我认为这可能与@ Jon-Clements在grep中提到的问题相同:python 2.2管道损坏 ,即管道已完成; but I'm not sure. 但我不确定。 I also tried (maybe incorrectly) the solution by @chepner store return value of a Python script in a bash script but it gives the same error. 我还尝试了bche 脚本中Python脚本的@chepner store返回值的解决方案(可能不正确),但它给出了相同的错误。

How can I fix this? 我怎样才能解决这个问题? I know that mixing BASH and Python is bad practice. 我知道将BASH和Python混合使用是不好的做法。

BTW, the python script is using a loop around the following statement to produce the list of filenames: 顺便说一句,python脚本正在以下语句周围使用循环来生成文件名列表:

print('"'+filename+'"',sep=" ",end=' ',) Also, when I copy and paste the output manually to less , it works fine. print('"'+filename+'"',sep=" ",end=' ',)此外,当我手动将输出复制并粘贴到less ,它可以正常工作。

Adding quotes around the file name isn't helpful. 在文件名周围添加引号没有帮助。 What you should do is 应该做的是

  1. Output each filename will a null byte between them. 输出每个文件名将在它们之间有一个空字节。
  2. Pipe the output to xargs -0 . 将输出传递给xargs -0

Quoting the filenames won't help unless you somehow use eval , which is not a good idea for security reasons. 除非您以某种方式使用eval ,否则引用文件名将无济于事,出于安全原因,这不是一个好主意。 Your command should look something like 您的命令应类似于

./myscript.py | xargs -0 less

As a hack, if the filenames are simple (ie no whitespace, no glob characters), you could modify ./myscript.py to output just the space-separated file names (no quotes), then run 作为一种hack,如果文件名很简单(即没有空格,没有全局字符),则可以修改./myscript.py以仅输出以空格分隔的文件名(不带引号),然后运行

less $(myscript.py)

since less only takes filename arguments. 因为less只使用文件名参数。

In bash < means redirects a file as standard input, and your python script is not a file. bash <表示将文件重定向为标准输入,并且您的python脚本不是文件。

You can use ./myscript.py | less 您可以使用./myscript.py | less ./myscript.py | less instead. ./myscript.py | less

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM