管道头的水管坏了导致shell脚本从蟒蛇叫 [英] Piping to head results in broken pipe in shell script called from python

查看:145
本文介绍了管道头的水管坏了导致shell脚本从蟒蛇叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命令我会运行生成随机字符串:

I have a command I would to run to generate random string:

var=`< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8`

当我在交互会话的bash命令我得到完全没有错误。但是,当我把这个命令放到脚本并运行它作为脚本我得到TR表示管道中断错误。我读过一些相关的主题,但仍然没有回答为什么脚本和交互行为是不同的,有没有办法用shell选项或别的东西来控制它?

When I run this command in interactive bash session I get absolutely no errors. But when I put this command into script and run it as a script I get Broken pipe error indicated by tr. I've read several related topics but still has no answer why script and interactive behavior is different and is there a way to control it with shell options or with something else?

修改我:

在关于给予意见,我发现表明水管坏的错误可以通过控制:

In regards to comments given I found that indicating broken pipe errors can be controlled via:

 trap - SIGPIPE # to ignore errors

 trap "" SIGPIPE # to display errors

修改二:

好吧,我提供了关于再现条件不正确的信息。最后,它似乎造成的Python包装,与使用os.system()调用的脚本这个问题:

Well, I've provided incorrect information about reproduction conditions. Finally it seems that problem caused with the python wrapper that called the script with the os.system():

 python -c "import os; os.system('sh -c \"< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8\"')"

定行独立生产使用的操作系统的水管坏的错误。

Line given produces broken pipe errors independently of used OS.

修改III:

这个主题已经在这里讨论:
https://mail.python.org/pipermail/python-dev /2005-September/056341.html

This topic has been discussed here: https://mail.python.org/pipermail/python-dev/2005-September/056341.html

推荐答案

如果父母中的一个处理陷阱 SIGPIPE ,然后管道将继承忽略信号配置,这将导致该问题,你遇到。

If one of the parent processes traps sigpipe, then the pipeline will inherit the ignore signal disposition, which will cause this problem you're experiencing.

这可能是(安全)与复制:

This can be (safely) reproduced with:

( trap '' pipe; var=`< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8 )

通常情况下,头-C8 命令来完成pretty很快此时其标准输入是关闭。由于它是标准输入是连接到标准输出 TR ,它现在不再使得 TR 写的标准输出。一旦尝试,该系统将与 SIGPIPE 杀死它。
除非 TR 忽略这个信号还是继承了忽略 SIG_IGN )配置为从其父此信号。然后,写的破 TR 标准输出会简单导致在这一点 TR 错误号 EPIPE C>将最有可能字符串化并输出错误的标准错误退出。

Normally, the head -c8 command will be done pretty soon at which point its stdin is closed. Since it's stdin is a pipe connected to the stdout of tr, it now no longer makes sense for tr to write to its stdout. Once it tries to, the system will kill it with SIGPIPE. Unless tr ignores this signal or has inherited the ignore (SIG_IGN) disposition for this signal from its parent. Then a write to tr's broken stdout will simply cause a regular error and set errno to EPIPE at which point tr will most likely stringify and outputs this error to its stderr and exit.

这篇关于管道头的水管坏了导致shell脚本从蟒蛇叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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