apt-get install输出在正常执行和从python执行时表现不同



我今天注意到apt的行为不同,这取决于它在哪里运行(shell/python/…)

我正在找"手表"的供货包装。通过apt CLI。手动操作也很好:

apt-get install -s watch
NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Keep also in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Note, selecting 'procps' instead of 'watch'
procps is already the newest version (2:3.3.15-2).
procps set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 15 not upgraded.

重要的一行是Note, selecting 'procps' instead of 'watch':显然,watch是由procps提供的。到目前为止一切顺利。

当我从python的subprocess库执行相同的命令时,这一行消失了。与os.system,它又工作了。

因此,我试图通过简单地将命令行(标准输出和标准错误)的输出管道放入日志文件(apt-get install -s watch &> /tmp/output)来调查这个问题。结果:

NOTE: This is only a simulation!
apt-get needs root privileges for real execution.
Keep also in mind that locking is deactivated,
so don't depend on the relevance to the real current situation!
Reading package lists...
Building dependency tree...
Reading state information...
procps is already the newest version (2:3.3.15-2).
procps set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 15 not upgraded.

缺少一行。

之后,我在apt的源代码中搜索了一下,找到了相应的行。这里的输出流是out,其他一些ioprintf部分使用c1out代替。所以这似乎是另一个流…但是为什么我的终端打印这个流的输出,而大多数其他程序不能处理它?

apt的行为取决于它的输出是否是tty。

如果它的stdout不是,它的行为就好像--quiet=1已经传递给它。

您可以通过显式传递--quiet=0来省略该行为。

apt-get --quiet=0 install -s watch | less

手册页可以告诉更多关于——quiet的信息。

请注意:依赖于apt开发人员使其难以管道化甚至grep/awk的东西很可能是一个坏主意。

您是否在虚拟环境中运行os.system?很有可能是因为那个原因。