How can I automatically answer yes in python? - python

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."""

Use the yes command:
yes Y | apt ...

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.

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.

Related

Installing Opencv3 in Python on Mac error

I am trying to install Opencv 3 for Python on Mac using this link (https://www.codingforentrepreneurs.com/blog/install-opencv-3-for-python-on-mac/)
I am using python 3.6.4 and I am currently at step 6 (regarding the link)
I am using Python directly from the Mac terminal and when I slot in the following command this error appears:
$ ln -S /usr/local/Cellar/opencv/3.4.0_1/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so /usr/local/lib/python3.6/site-packages/cv2.so
File "<stdin>", line 1
ln -S /usr/local/Cellar/opencv/3.4.0_1/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so /usr/local/lib/python3.6/site-packages/cv2.so
^
SyntaxError: invalid syntax
You essentially need to run a command like:
ln -s SRC TGT
where SRC is the library you have just built/installed and TGT is where you want it to be visible to Python.
Find the SRC file, independently of the OpenCV versions you have installed, like this:
SRC=$(find /usr/local/Cellar/opencv -name "cv2.cpython*so")
and check it looks correct with:
echo "$SRC"
There should be one line. If there is more than one line, it means you have multiple versions of OpenCV installed, so it may look like:
/usr/local/Cellar/opencv/3.4.0_1/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so
/usr/local/Cellar/opencv/3.3.1_7/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so
In that case, choose the one you want and manually set SRC to that one, e.g.
SRC=/usr/local/Cellar/opencv/3.4.0_1/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so
Find the TGT directory, independently of the Python versions you have installed, like this:
TGT=$(find /usr/local/lib/ -type d -name "site-packages")
and check it looks correct with:
echo "$TGT"
There should be one line. If there is more than one line, it means you have multiple versions of Python installed, and it may look something like:
/usr/local/lib/python3.6/site-packages
/usr/local/lib/python3.5/site-packages
If that is the case, choose the one you want to use and set TGT manually, e.g.:
TGT=/usr/local/lib/python3.6/site-packages
Now make the link:
ln -s "$SRC" "$TGT/cv2.so"
In step 6, you first get the sys path, notice that this is done while running python.
You can tell because of the prompt ">>>" in
>>> print(sys.path)
If you then enter:
ln -s /usr/local/Cellar/opencv/3.4.1_4/....
While in Python, you will get the exact error you mentioned.
In order to finish step 6 you now must exit python by typing
>>> exit()
Now you will see the $ prompt.
I realize the way you stated your problem that you were already at the $ prompt, so this might be moot... but if you typed your question rather than cutting and pasting it, maybe you typed it incorrectly here and you were actually still in Python when you had the error.
$ ln -s /usr/local/Cellar/opencv/3.4.1_4/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so /usr/local/lib/python3.6/site-packages/cv2.so

excludepkgs yum python API

I am trying to write python script to update the packages ( similar to yum update).
Following script enabled 2 repo's ( which I want to use) and then run yum update. Its working fine but I want to exclude some packages ( example any package starts from "kernel*"). I was checking the API yum documentation but didn't find examples. I see that there is function called excludePackages(repo=None) but I am not sure how to pass the lists of packages there or how to use this function.
Can someone please help?
#! /usr/env python
import yum
import os
import sys
yb = yum.YumBase()
yb.setCacheDir()
print "Enabled repos are:"
yb.repos.disableRepo("*")
for name in ('reponame1','reponame2'):
yb.repos.enableRepo(name + ',')
for repo in yb.repos.listEnabled(): #checking the enabled repos
print "%s" %(repo.id)
yb.update()
yb.resolveDeps()
yb.buildTransaction()
yb.processTransaction()
yb.processTransaction(rpmDisplay=yum.rpmtrans.NoOutputCallBack())
yb.doUnlock()
You need to set the exclude list per repo, globally or via the command line.
repo.setAttribute('exclude', ['kernel*'])
References
http://yum.baseurl.org/api/yum-3.2.27/yum.repos-pysrc.html#Repository.setAttribute
http://yum.baseurl.org/api/yum-3.2.27/yum.repos-pysrc.html#Repository.getExcludePkgList
http://yum.baseurl.org/api/yum-3.2.27/yum-pysrc.html#YumBase.excludePackages

Calling 'make' from Python inside Vagrant VM

Okay, so this question is very project-specific, but it's a problem for me nonetheless.
I have a Python/django website, hosted on localhost from an Ubuntu VM set up by Vagrant. From this website I want to paste in C code and compile it via a series of Python functions. In one of these functions I call make like this:
arg2 = os.path.join(Default_SDK_PATH, "examples/peripheral/blinky")
arg4 = os.path.join(Default_SDK_PATH, "examples/peripheral/blinky/makefile")
args = ' '.join(['make', '-C', arg2, '-f', arg4])
p = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True
)
output, errors = p.communicate()
p.wait()
I specify arg2 and arg4 more for testing than anything else - It's just to be 100% sure that the correct makefile is used.
### ### ###
OK!
So my problem comes when the subprocess runs. The makefile is called with make, but failes. When I check the build log I can see the error message arm-none-eabi-gcc: error: nano.specs: No such file or directory.
When I call vagrant up for the first time a file named bootstrap.sh is called. I've tried adding new commands to this file
sudo apt-get remove binutils-arm-none-eabi gcc-arm-none-eabi
sudo add-apt-repository ppa:terry.guo/gcc-arm-embedded
sudo apt-get update
sudo apt-get install gcc-arm-none-eabi=4.9.3.2015q1-0trusty13
to uninstall Ubuntu's original GCC and install the latest GCC toolchain. No success there either. I've also tried returning the whole filestructure to file just to check if the files in question exists, and they do!
Can anyone point me in the right direction here?
Thanks in advance.
Whoop-di-hoo, I solved it!
I don't exactly know why, but sudo apt-get remove binutils-arm-none-eabi gcc-arm-none-eabi doesn't seem to do anything, so the original GCC-files still exist when I try to install the new GCC.
Also, the new GCC is installed in /usr/bin, while the old GCC has it's own specified folder.
So I edited my Makefile to get arm-none-eabi-gcc-4.9.3 from /usr/bin instead of the old arm-none-eabi-gcc. nano.specs is now included, and life is great!

Determine if package installed with Yum Python API?

TLDR; I need simple a Python call given a package name (e.g., 'make') to see if it's installed; if not, install it (I can do the latter part).
Problem:
So there are a few code examples given in http://yum.baseurl.org/wiki/YumCodeSnippets, but other than kludging around inside ipython and guessing at what each method does, there doesn't appear to be any actual documentation for the Python API for yum. It's apparently all tribal knowledge.
[edit] Apparently I just accidentally discovered the API documentation (after receiving an acceptable answer, of course). It's not linked from the main page, but here it is for future reference: http://yum.baseurl.org/api/yum/
What I need to do:
I have a deployment configuration script that relies on other system packages (make, gcc, etc.). I know I can install them like this: http://yum.baseurl.org/wiki/YumCodeSnippet/SimplestTransaction but I'd like to have the option to query if they're already installed before doing so, so I can have the additional option of simply failing if the packages aren't present instead of forcing installation. What's the proper call to do this (or better, has anyone actually bothered to properly document the API outside of code samples?)
I've never touched Python prior to this project, and I'm really liking it, but... some of the module documentation is more elusive than unicorn-riding leprechauns.
import yum
yb = yum.YumBase()
if yb.rpmdb.searchNevra(name='make'):
print "installed"
else:
print "not installed"
You could run 'which' on the subsystem to see if the system has the binaries you are looking for:
import os
os.system("which gcc")
os.system("which obscurepackagenotgoingtobefound")
For anyone who stumbles across this post later, here's what I came up with. Note that "testing" and "skip_install" are flags that I parse from the script invocation.
print "Checking for prerequisites (Apache, PHP + PHP development, autoconf, make, gcc)"
prereqs = list("httpd", "php", "php-devel", "autoconf", "make", "gcc")
missing_packages = set()
for package in prereqs:
print "Checking for {0}... ".format([package]),
# Search the RPM database to check if the package is installed
res = yb.rpmdb.searchNevra(name=package)
if res:
for pkg in res:
print pkg, "installed!"
else:
missing_packages.add(package)
print package, "not installed!"
# Install the package if missing
if not skip_install:
if testing:
print "TEST- mock install ", package
else:
try:
yb.install(name=package)
except yum.Errors.InstallError, err:
print >> sys.stderr, "Failed during install of {0} package!".format(package)
print >> sys.stderr, str(err)
sys.exit(1)
# Done processing all package requirements, resolve dependencies and finalize transaction
if len(missing_packages) > 0:
if skip_install:
# Package not installed and set to not install, so fail
print >> sys.stderr, "Please install the {0} packages and try again.".format(
",".join(str(name) for name in missing_packages))
sys.exit(1)
else:
if testing:
print "TEST- mock resolve deps and process transaction"
else:
yb.resolveDeps()
yb.processTransaction()
import yum
yb = yum.YumBase()
yb.isPackageInstalled('make')

Is there a way to add a ppa using the python apt module?

I need to add a ppa to remote servers using a python script. The bash equivalent of what I want to do is:
$ add-apt-repository ppa:user/ppa-name
I'm assuming it would look something like this:
import apt
cache = apt.Cache()
# ?? add the ppa here ??
cache.update()
cache.open(None)
cache['package_from_ppa'].mark_install()
cache.upgrade()
cache.commit()
but I haven't been able to find much in the apt module source related to adding repositories.
taken from the current (in 11.04 natty) add-apt-repository code:
from softwareproperties.SoftwareProperties import SoftwareProperties
sp = SoftwareProperties()
sp.add_source_from_line(ppa_name)
sp.sourceslist.save()
You should of cause add checks for errors, etc...
look at the currently installed version like this:
less `which add-apt-repository`
I noticed op never got the answer he wanted so here is the solution.
import aptsources.sourceslist as s
repo = ('deb', 'http://ppa.launchpad.net/danielrichter2007/grub-customizer/ubuntu', 'xenial', ['main'])
sources = s.SourcesList()
sources.add(repo)
sources.save()

Categories