【问题标题】:apt-get install output behaves differently when executed normally and from pythonapt-get install 输出在正常执行和从 python 执行时的行为不同
【发布时间】:2021-10-02 09:29:14
【问题描述】:

我今天注意到 apt 的行为因运行位置(shell / python / ...)而异。

背景 我正在尝试通过 apt CLI 查找“watch”的提供包。这也很有效:

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,它又可以工作了。

所以我试图通过简单地将命令行(stdout 和 stderr)的输出传送到日志文件(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 的源代码中搜索了一下,找到了corresponding line。这里的输出流是out,其他一些ioprintf 部分正在使用c1out。所以这似乎是另一个流......但是为什么我的终端打印这个流的输出而大多数其他程序都无法处理它?

【问题讨论】:

    标签: stream pipe apt


    【解决方案1】:

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

    【讨论】:

    • 是的,我的包在虚拟环境中运行。但是在外部(系统python)它仍然可以工作。
    【解决方案2】:

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

    如果它的标准输出不是,它的行为就好像--quiet=1 已被传递给它。

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

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

    手册页可以提供更多关于 --quiet 的信息。

    请注意: 依赖 apt-developer 更难管理甚至 grep/awk 的东西很可能是个坏主意。

    【讨论】:

    • 对于已安装的软件包,我建议使用dpkg -S。对于那些不必要的,你可以使用apt-file find /usr/bin/watch
    猜你喜欢
    • 2014-05-06
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多