how to download a package with python-apt? - python-2.7

I want to know as title says: how to download a package using python-apt API? Only download it, don't to install it, just like does the command:
apt-get download ${package_name}
I'm using python v2.7.5-5ubuntu3 with python-apt v0.9.3.5 on Ubuntu 14.04.

You can use this script
#!/usr/bin/python
import apt
import os, sys
if len(sys.argv) != 2:
print 'Usage: apt-download pkg_name'
sys.exit()
cache = apt.Cache()
pkg = cache[sys.argv[1]]
cmd = 'wget ' + pkg.candidate.uri
print cmd
os.system(cmd)
It works well with Python 2.7.8 and python-apt 0.9.3.11 but it should also work with your configuration.

Related

How can I write a unit test for python3's webbrowser module?

I want to unit test a bunch of code that looks like this:
# First command. This will open reddit in your browser.
# -------------------------------------------------------------
if 'open reddit' in command:
url = 'https://www.reddit.com/'
if not runtest:
webbrowser.open(url)
print('Done!')
talktome.talkToMe('reddit is opening.')
if runtest:
return url
# -------------------------------------------------------------
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I've written this unit test:
import unittest
import subprocess
from GreyMatter import julibrain
from SpeakAndHear import talktome
class TestBrain(unittest.TestCase):
def test_open_reddit(self):
test = True
testurl = julibrain.assistant('open reddit', 1, 2, test)
#subprocess.call(['pip', 'list', '|', 'grep', 'webbrowser'])
self.assertEqual(testurl, 'https://www.reddit.com/')
I invoke it on the command line:
python -m unittest test_julibrain.py
It gives me this output:
python -m unittest test_julibrain.py
Package Version
----------------- ----------
autopep8 1.5.2
beautifulsoup4 4.9.0
certifi 2020.4.5.1
chardet 3.0.4
click 7.1.1
future 0.18.2
gTTS 2.1.1
gTTS-token 1.1.3
idna 2.9
isort 4.3.21
lazy-object-proxy 1.4.3
mccabe 0.6.1
mock 4.0.1
MouseInfo 0.1.3
mypy 0.770
mypy-extensions 0.4.3
numpy 1.18.1
Pillow 7.1.1
pip 20.0.2
psutil 5.7.0
PyAudio 0.2.11
PyAutoGUI 0.9.50
pycodestyle 2.5.0
PyGetWindow 0.0.8
pylint 2.4.4
PyMsgBox 1.0.7
pyperclip 1.8.0
PyQt5 5.14.2
PyQt5-sip 12.7.2
PyRect 0.1.4
PyScreeze 0.1.26
python3-xlib 0.15
PyTweening 1.0.3
requests 2.23.0
setuptools 45.2.0
six 1.14.0
soupsieve 2.0
subprocess.run 0.0.8
typed-ast 1.4.1
typing-extensions 3.7.4.1
urllib3 1.25.9
vosk 0.3.3
wheel 0.34.2
wikipedia 1.4.0
wrapt 1.11.2
.
----------------------------------------------------------------------
Ran 1 test in 0.285s
OK
So I can test that the url is being set, but I don't know how to see if the webbrowser module is working. If I run the code, it the webbrowser opens. I don't want to open it. I'd like to get back some sort of status that says the module has been imported, a webbroser object can be instantiated, and there are no problems. After looking at the webbrowser doc, I have no idea how to do this. Any ideas? Thank you. I'm on Ubuntu 18.04, using conda and python 3.6.1. Cheers!

Python Jupyter Notebook how can I list the /root directory.

I can list the root directory using a script file and command line.
%%writefile ShowDir.py
import os
import sys
from sys import argv
DIR = argv[1]
show = os.listdir(DIR)
print show
Then I ran in the terminal:
!echo mypassword | sudo -S python ShowDir.py /root
It worked, but I want a more graceful approach.
I also tried:
This will run files, make directories, remove files directories, but for some reason will not LIST them.
import os, subprocess
ret = subprocess.check_call("echo mypassword | sudo -S ls /root", shell=True)
ret
It just returned a 0, no directory listing

memcache on django is not working

I have a race condition in Celery. Inspired by this - http://ask.github.io/celery/cookbook/tasks.html#ensuring-a-task-is-only-executed-one-at-a-time I decided to use memcache to add locks to my tasks.
These are the changes I made:
python-memcached
# settings for memcache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
After this I login to my shell and do the following
>>> import os
>>> import django
>>> from django.core.cache import cache
>>> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings.base')
>>> cache
<django.core.cache.DefaultCacheProxy object at 0x101e4c860>
>>> cache.set('my_key', 'hello, world!', 30) #display nothing. No T/F
>>> cache.get('my_key') #Display nothing.
>>> from django.core.cache import caches
>>> caches['default']
<django.core.cache.backends.memcached.MemcachedCache object at 0x1048a5208>
>>> caches['default'].set('my_key', 'hello, world!', 30) #display nothing. No T/F
>>> caches['default'].get('my_key') #Display nothing.
also did pip install python-memcached
Using Python 3.6, Django==1.10.5
What am I doing wrong? Any help will be appreciated.
The problem was, memcached was killed for some reason and I was assumed it was still running. My bad.
Now it works all perfectly.
For anyone who is stuck on a similar problem you want to make sure you are still running memcached, try memcached -vv
Keeping this here for reference.
If your install is looking like mine is starting to look (in which case, you have my sympathies; for RHEL is one platform where django seems thinner on-the-ground than this-week's python):
# yum upgrade -y
yum-config-manager --add-repo=https://dl.fedoraproject.org/pub/epel/7/x86_64/
# yum install -y emacs-nox
yum install -y python{-sqlparse,36{,-{devel,pip,pytz,bcrypt}}} memcached
service memcached start
chkconfig memcached on
python36 \
-m pip install \
django \
pymemcache \
--no-deps --upgrade
then checking the status on memcache is as easy with the same commands we've been using for 20 years:
service memcached status
There are other commands one can use on RHEL/EL7 (#fridgeArt), but I prefer compatible workflows in spite of resume-driven differentiation. >:-(
Here's how to launch it with -vv under EL and debuntus too: https://stackoverflow.com/a/22239764/2066657

Running shell commands sequentially in one shell with subprocess

I am having difficulties running a series of sequential commands using the subprocess module, i need to do this so a python program can call in an installation of a cv virtualenv and then run another python program (that needs to be run within the virtualenv)
This is the command string i run from terminal, you can see it contains multiple commands that run in sequence until the creation of the cv virtual env:
sudo pip install virtualenv virtualenvwrapper && sudo rm -rf ~/.cache/pip && export WORKON_HOME=$HOME/.virtualenvs && source /usr/local/bin/virtualenvwrapper.sh && source ~/.bashrc && mkvirtualenv cv
Running this in the terminal returns me something like this:
(cv) name#computer:~$
from that i can run my python scripts that need the openCV
my code so far is this:
from subprocess import Popen, PIPE, STDOUT
cmd1 = 'sudo pip install virtualenv virtualenvwrapper'
cmd2 = 'sudo rm -rf ~/.cache/pip'
cmd3 = 'export WORKON_HOME=$HOME/.virtualenvs'
cmd4 = 'source /usr/local/bin/virtualenvwrapper.sh'
cmd5 = 'source ~/.bashrc'
cmd6 = 'mkvirtualenv cv'
cmd7 = 'cd /script path'
cmd8 = 'python novo.py'
final = Popen("{}; {}; {}; {}; {}; {}; {}; {}".format(cmd1, cmd2,cmd3, cmd4, cmd5, cmd6, cmd7, cmd8), shell=True, stdin=PIPE,
stdout=PIPE, stderr=STDOUT, close_fds=True)
stdout, nothing = final.communicate()
log = open('log', 'w')
log.write(stdout)
log.close()
And the errors in log look like this:
/bin/sh: 1: source: not found
/bin/sh: 1: source: not found
/bin/sh: 1: mkvirtualenv: not found
How can i achieve a terminal like execution ?
again, sequence is crucial.
/bin/sh: 1: source: not found
shell=True uses /bin/sh by default. source shell builtin hints at bash. Pass executable='/bin/bash'.
btw, you could use a multiline string literal:
#!/usr/bin/env python3
import sys
from subprocess import check_call, DEVNULL, STDOUT
with open('log', 'wb', 0) as file:
check_call("""set -e -x
{python} -mpip install --user virtualenv virtualenvwrapper
rm -rf ~/.cache/pip
export WORKON_HOME=$HOME/.virtualenvs
source /path/to/virtualenvwrapper.sh
source ~/.bashrc
mkvirtualenv cv
cd /script path
{python} novo.py
""".format(python=sys.executable),
shell=True, executable='/bin/bash',
stdin=DEVNULL, stdout=file, stderr=STDOUT, close_fds=True)
Or save the command into a separate bash script and run the script instead.
DEVNULL is Python 3 feature—it is easy to emulate it on Python 2 too: DEVNULL = open(os.devnull, 'r+b', 0).

pywin32 and pyttsx error, trouble combining the two

i have pywin32 in my site packages and my pyttsx is in a separate folder. Is this the reason why i am getting the following error?
import win32api, sys, os
ImportError: DLL load failed: The specified module could not be found
The code is as follows,
import pyttsx
def onStart(name):
print 'starting', name
def onWord(name, location, length):
print 'word', name, location, length
def onEnd(name, completed):
print 'finishing', name, completed
engine = pyttsx.init()
engine.connect('started-utterance', onStart)
engine.connect('started-word', onWord)
engine.connect('finished-utterance', onEnd)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
from here, http://pyttsx.readthedocs.org/en/latest/engine.html#examples
My pywin32 is from here,
http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/
for Py 2.7
The problem was that the file
pywintypes27.dll
was not in the right directory. It had to be in
'C:\Windows\System32'
#CristiFati
Use the pyttsx3 module instead . It supports both python3 and python2.
To install:
pip install pyttsx3.
It automatically installs those win32 and other dependencies.