How can I automatically answer yes in python?

2019-08-01 04:16发布

问题:

Say I have a script that runs apt upgrade -y later on I'll need to manually answer these questions for different packages. How can I automatically do that?

Setting up virtualbox-guest-x11 (5.0.32-dfsg-0ubuntu1.16.04.2) ...

Configuration file '/etc/X11/Xsession.d/98vboxadd-xclient'
 ==> File on system created by you or by a script.
 ==> File also in package provided by package maintainer.
   What would you like to do about it ?  Your options are:
    Y or I  : install the package maintainer's version
    N or O  : keep your currently-installed version
      D     : show the differences between the versions
      Z     : start a shell to examine the situation
 The default action is to keep your current version.
*** 98vboxadd-xclient (Y/I/N/O/D/Z) [default=N] ?  conffile prompt detected: /etc/X11/Xsession.d/98vboxadd-xclient /etc/X11/Xsession.d/98vboxadd-xclient.dpkg-new

My script is able to detect the confile prompt but how should I go about answering yes automatically?

by using python-apt api I am able to detect the prompt via this funtion

def conffile(self, current, new):
    print " conffile prompt detected: %s %s" % (current, new)

    """(Abstract) Called when a conffile question from dpkg is detected."""

回答1:

Since (per comment under the question) you're using Python-APT, the first way that comes to mind is using the Configuration class to set conf['APT::Get::Assume-Yes'] = True.



回答2:

Use the yes command:

yes Y | apt ...


回答3:

For all those who were lost like me, the answer is:

import apt_pkg

apt_pkg.init_config()
apt_pkg.config.set("DPkg::Options::", "--force-confnew")

This will make apt automatically accept new config files.