text
stringlengths 226
34.5k
|
---|
Inform OS of installation
Question: Just a question that interested me, I noticed that modern installers (for
various types of programs) alert you to wait until another installation is
finished before running themselves.
**How can I check for that / notify other installers?**
_Using c# or python_
Answer: AFAIK there is no way to "find" other running installers. At least not on
every system and every installer. The only good way is to use an installer
which supports that like windows installer (but also that only checks for
other running windows installers).
A probably working way would be to use a list of process names of installers
and check if one of them is running.
Another way found as answers
[this](http://stackoverflow.com/questions/9125966/checking-if-windows-update-
or-any-installer-instace-is-running-before-starting-m) question is to check a
registry key ([1](http://stackoverflow.com/a/9160083/2325172)) or use the
windows api ([2](http://stackoverflow.com/a/9247466/2325172)). But this two
ways would only work on windows.
For ways to check if a process is running you could use the python module
[psutil](http://code.google.com/p/psutil/). An example which prints all
process names would be:
import psutil
for p in psutil.process_iter():
print p.name
|
How to batch asynchronous web requests performed using a comprehension in python?
Question: not sure if this is possible, spend some time looking at what seem like
similar questions, but still unclear. For a list of website urls, I need to
get the html as a starting point.
I have a class that contains a list of these urls and the class returns a
custom iterator that helps me iterate through these to get the html
(simplified below)
class Url:
def __init__(self, url)
self.url = url
def fetchhtml(self)
import urllib2
response = urllib2.urlopen(self.url)
return response.read()
class MyIterator:
def __init__(self, obj):
self.obj=obj
self.cnt=0
def __iter__(self):
return self
def next(self):
try:
result=self.obj.get(self.cnt)
self.cnt+=1
return result
except IndexError:
raise StopIteration
class Urls:
def __init__(self, url_list = []):
self.list = url_list
def __iter__(self):
return MyIterator(self)
def get(self, index):
return self.list[index]
2 - I want to be able to use like
url_list = [url1, url2, url3]
urls = Urls(url_list)
html_image_list = {url.url: re.search('@src="([^"]+)"', url.fetchhtml()) for url in urls}
3 - problem i have is that I want to batch all the requests rather than having
fetchhtml operate sequentially on my list, and once they are done then extract
the image list.
Is there ways to to achieve this, maybe use threads and queue? i cannot see
how to make the the list comprehension for my object work like this without it
running sequentially. Maybe this is the wrong way, but i just want to batch
long running requests initiated by operations within a list or dict
comprehension. Thankyou in advance
Answer: you need to use `threading` or `multiprocessing`.
also, in Python3, there is
[`concurrent.futures`](http://docs.python.org/3/library/concurrent.futures.html).
Take a look at `ThreadPoolExecutor` and `ProcessPoolExecutor`.
The [example in the
docs](http://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor)
for `ThreadPoolExecutor` does almost exactly what you are asking:
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the url and contents
def load_url(url, timeout):
conn = urllib.request.urlopen(url, timeout=timeout)
return conn.readall()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
* Note: similar functionality is available for Python 2 via the [`futures`](https://pypi.python.org/pypi/futures) package on PyPI.
|
Installation issues for Virtualenv and VirtualenvWrapper in Ubuntu 13.04
Question: Ubuntu Server in VirtualBox. I am trying to install VirtualEnv to start
learning Flask and bottle. Some details of my setup.
vks@UbSrVb:~$ cat /etc/os-release
NAME="Ubuntu"
VERSION="12.04.2 LTS, Precise Pangolin"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu precise (12.04.2 LTS)"
VERSION_ID="12.04"
vks@UbSrVb:~$ python --version
Python 2.7.3
vks@UbSrVb:~$ echo $VIRTUALENVWRAPPER_PYTHON
/usr/bin/python
vks@UbSrVb:~$ echo $VIRTUALENV_PYTHON
vks@UbSrVb:~$
When I boot my Virtual Machine, I get the following error on my console
/usr/bin/python: No module named virtualenvwrapper
virtualenvwrapper.sh: There was a problem running the initialization hooks.
If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenv has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is
set properly.
When i try to initialize a virtualenv I get the following errors
vks@UbSrVb:~/dropbox/venv$ virtualenv try1
New python executable in try1/bin/python3.2
Also creating executable in try1/bin/python
Traceback (most recent call last):
File "/usr/local/bin/virtualenv", line 9, in <module>
load_entry_point('virtualenv==1.9.1', 'console_scripts', 'virtualenv')()
File "/usr/local/lib/python3.2/dist-packages/virtualenv.py", line 979, in main
no_pip=options.no_pip)
File "/usr/local/lib/python3.2/dist-packages/virtualenv.py", line 1081, in create_environment
site_packages=site_packages, clear=clear))
File "/usr/local/lib/python3.2/dist-packages/virtualenv.py", line 1499, in install_python
os.symlink(py_executable_base, full_pth)
OSError: [Errno 30] Read-only file system
vks@UbSrVb:~/dropbox/venv$ ls
try1
vks@UbSrVb:~/dropbox/venv$ ls try1/
bin include lib
vks@UbSrVb:~/dropbox/venv$
My .bashrc entries
export WORKON_HOME='~/dropbox/venv/'
source '/usr/local/bin/virtualenvwrapper.sh'
Q1 - As per the error at bootup, How do I ensure _virtualenv_ is installed for
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is set properly ?
Q2 - Even with sudo I get the same "Read-only file system" Error ?
_I have tried installing virtualenv using pip and then apt-get, just to hit
and try._
Answer: Try setting your WORKON_HOME global to another path (~/.virtualenvs) for
example a see if that works, maybe the problem is with that shared directory,
are you using windows? If you are, try installing ntfs-3g, see
<http://askubuntu.com/questions/70281/why-does-my-ntfs-partition-mount-as-
read-only>
Also in my profile configuration file I like to detect first if
virtualenvwrapper is installed:
if which virtualenvwrapper.sh &> /dev/null; then
WORKON_HOME=$HOME/.virtualenvs
# path to virtualenvwrapper, in my case
source /usr/local/share/python/virtualenvwrapper.sh
fi
|
Python scripts on DD-WRT embedded router
Question: I've written two Python (2.x) scripts to perform the following:
1. Custom Proxy server (imports optparse, ConfigParser, TLDextract, SocketServer...)
2. Web admin for proxy (imports flask, ConfigParser, netifaces...)
These are both currently running on a Raspberry pi (Raspian), however I'm
seeking some advice on some options on how to get these to run on a DDWRT
router (v24).
My thoughts are either:
1. Install python and required libraries on DDWRT. Whilst I have found some evidence that python can be installed via ipkg (on USB storage) I'm not clear how to get the required imported libraries installed too?
2. Create a python-independent binary (e.g. PyInstaller) to run on DDWRT. I have hesitations going down this path as I imagine that I'd need to perform the task on a DDWRT running Python (i.e. back to thought 1), and also how it would handle the imported libraries?
3. Similar to point 1: Compile a custom OpenWRT image which includes all required Python packages. This does seem like a complex piece of work.
Appreciate any advise that you may have.
Answer: You will need to use optware to get the packages and install them onto your
router. There is a very good tutorial on the [DD-WRT website](http://www.dd-
wrt.com/wiki/index.php/Optware,_the_Right_Way). Through optware you can
install the different python packages. Do mind that running flask and a
proxyserver on a DDWRT router with a limited amount of memory might not be the
best idea.
|
Understanding Popen.communicate
Question: I have a script named `1st.py` which creates a REPL (read-eval-print-loop):
print "Something to print"
while True:
r = raw_input()
if r == 'n':
print "exiting"
break
else:
print "continuing"
I then launched `1st.py` with the following code:
p = subprocess.Popen(["python","1st.py"], stdin=PIPE, stdout=PIPE)
And then tried this:
print p.communicate()[0]
It failed, providing this traceback:
Traceback (most recent call last):
File "1st.py", line 3, in <module>
r = raw_input()
EOFError: EOF when reading a line
Can you explain what is happening here please? When I use `p.stdout.read()`,
it hangs forever.
Answer: `.communicate()` writes input (there is no input in this case so it just
closes subprocess' stdin to indicate to the subprocess that there is no more
input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by `raw_input()` (it
expected data but got EOF (no data)).
`p.stdout.read()` hangs forever because it tries to read _all_ output from the
child at the same time as the child waits for input (`raw_input()`) that
causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using
threads or select) or to know exactly when and how much to read/write, [for
example](http://ideone.com/Dr3pQi):
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of [block-buffering issue](http://stackoverflow.com/q/443057/4279)
(here it is solved by using ["-u" flag that turns off buffering for stdin,
stdout _in the child_](http://docs.python.org/2/using/cmdline.html)).
[`bufsize=1` makes the pipes line-buffered _on the parent
side_](http://docs.python.org/2/library/subprocess#popen-constructor).
|
python access selective files with glob module
Question: I have a collection of binary files which have names as so:
d010-recomb.bin
d011-recomb.bin
.............
.............
.............
d100-recomb.bin
Using the python glob module, i can access all the files in a folder and can
do further processing with these files:
import glob
binary = sorted(glob.glob('C:/Users/Desktop/bin/*.bin'))
I can also use some criteria for the files that I want to access:
FOr example if I use the following code then I will gain access to all the
files from d010-recomb.bin to d019-recomb.bin
binary = sorted(glob.glob('C:/Users/Desktop/bin/d01*.bin'))
But using this criteria I can't get access to files such as d015 to d025.
**Please** tell me what I can do to gain access to these files.
Answer: You can either filter list, using:
def filter_path(path,l,r):
i = int(os.path.basename(path)[1:4])
if (i >= l) and (i <= r):
return True
return False
result = [i for i in binary if filter_path(i,19,31)]
If you are 100% confident about number of elements in directory, you can:
result = binary[19:30]
Or once you have data sorted, you may find the _first index_ and the _last
index_ and [[1]](http://stackoverflow.com/questions/176918/in-python-how-do-i-
find-the-index-of-an-item-given-a-list-containing-
it)[[2]](http://docs.python.org/3.2/tutorial/datastructures.html):
l = binary.find('C:/Users/Desktop/bin/d015.bin')
r = binary.find('C:/Users/Desktop/bin/d023.bin')
result = binary[l:r+1]
|
Where do I initialize my webdriver in Django using Selenium along django.test
Question: I am willing to test my Django application using Selenium. From what I read,
Django already cover the testing part and allow you to write your own tests.
Willing to use this with Selenium, here is my `<application>/test.py`:
from some.path.to.my.utilitary.module import TestTools
class FormTestCase(TestCase):
def setUp(self):
self.webui = TestTools()
def test_advanced_settings(self):
self.webui.go_to('home')
self.webui.click('id', 'button-advanced-settings')
self.webui.click('id', 'id_setting_0')
self.webui.click('id', 'id_setting_1')
self.webui.click('id', 'id_setting_2')
self.webui.click('id', 'id_setting_3', submit=True)
def test_zone_selector(self):
self.webui.go_to('home')
self.webui.click('id', 'button-zone-selector')
I've written a Python class in which I implemented the Selenium logic
(`TestTools`), so I can focus on writing test code in my Django applications:
class TestTools():
def __init__(self):
self.driver = webdriver.Firefox(...)
...
# Those methods use self.driver to do things
def click(...):
...
def go_to(...):
...
def quit(...):
...
I noticed I couldn't override the `__init__` method in the `TestCase` child,
so I put the `self.webui = TestTools()` in the `setUp` method. However, it is
called twice (for each test method I guess), and thus create 2 webdrivers.
What I want to do is running `./manage test`, opening only one browser and
running all my tests upon it. Where should the webdriver initialization live ?
Thanks,
Answer: Here's my insight.
I prefer to create a custom `TestCase` based on
[LiveServerTestCase](https://docs.djangoproject.com/en/dev/topics/testing/overview/#django.test.LiveServerTestCase):
class SeleniumTestCase(LiveServerTestCase):
"""
A base test case for selenium, providing different helper methods.
"""
def setUp(self):
self.driver = WebDriver()
def tearDown(self):
self.driver.quit()
def open(self, url):
self.driver.get("%s%s" % (self.live_server_url, url))
Then, all my test cases are derived from this `SeleniumTestCase`.
Hope that helps.
|
Cython, Python and KeyboardInterrupt ignored
Question: Is there a way to interrupt (`Ctrl+C`) a Python script based on a loop that is
embedded in a Cython extension?
I have the following python script:
def main():
# Intantiate simulator
sim = PySimulator()
sim.Run()
if __name__ == "__main__":
# Try to deal with Ctrl+C to abort the running simulation in terminal
# (Doesn't work...)
try:
sys.exit(main())
except (KeyboardInterrupt, SystemExit):
print '\n! Received keyboard interrupt, quitting threads.\n'
This runs a loop that is part of a C++ Cython extension. Then, while pressing
`Ctrl+C`, the `KeyboardInterrupt` is thrown but ignored, and the program keeps
going until the end of the simulation.
The work around I found, is to handle the exception from within the extension
by catching the `SIGINT` signal :
#include <execinfo.h>
#include <signal.h>
static void handler(int sig)
{
// Catch exceptions
switch(sig)
{
case SIGABRT:
fputs("Caught SIGABRT: usually caused by an abort() or assert()\n", stderr);
break;
case SIGFPE:
fputs("Caught SIGFPE: arithmetic exception, such as divide by zero\n",
stderr);
break;
case SIGILL:
fputs("Caught SIGILL: illegal instruction\n", stderr);
break;
case SIGINT:
fputs("Caught SIGINT: interactive attention signal, probably a ctrl+c\n",
stderr);
break;
case SIGSEGV:
fputs("Caught SIGSEGV: segfault\n", stderr);
break;
case SIGTERM:
default:
fputs("Caught SIGTERM: a termination request was sent to the program\n",
stderr);
break;
}
exit(sig);
}
Then :
signal(SIGABRT, handler);
signal(SIGFPE, handler);
signal(SIGILL, handler);
signal(SIGINT, handler);
signal(SIGSEGV, handler);
signal(SIGTERM, handler);
Can't I make this work from Python, or at least from Cython instead ? As I am
about to port my extension under Windows/MinGW, I would appreciate to have
something less Linux specific.
Answer: You have to periodically check for pending signals, for example, on every Nth
iteration of the simulation loop:
from cpython.exc cimport PyErr_CheckSignals
cdef Run(self):
while True:
# do some work
PyErr_CheckSignals()
`PyErr_CheckSignals` will run signal handlers installed with
[signal](http://docs.python.org/2/library/signal.html) module (this includes
raising `KeyboardInterrupt` if necessary).
`PyErr_CheckSignals` is pretty fast, it's OK to call it often. Note that it
should be called from the main thread, because Python runs signal handlers in
the main thread. Calling it from worker threads has no effect.
**Explanation**
Since signals are delivered asynchronously at unpredictable times, it is
problematic to run any meaningful code directly from the signal handler.
Therefore, Python queues incoming signals. The queue is processed later as
part of the interpreter loop.
If your code is fully compiled, interpreter loop is never executed and Python
has no chance to check and run queued signal handlers.
|
Adding two number isn't working on heroku
Question: Why this code is not running on heroku? (Internal server error)
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
a = 10
b = 20
c = a + b
return c
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Logs:
Starting process with command `python app.py`
a = 1
^
SyntaxError: invalid syntax
File "app.py", line 8
This code is working (Python hello world from heroku guides)
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
Answer: Sounds like that not your code is being executed. After all your line was `a =
10` and the log file complains about a line stating `a = 1`.
Or maybe there's a strange (invisible?) character between the `1` and the `0`.
I'd propose to change that value from `10` to `42` for testing and see in what
way the error log message changes.
|
Python & Tide SDK - import external module?
Question: Since python is bundled with the Tide SDK, I can't figure out how to use
access external modules. I've tried copying the module folder "Lib/site-
packages/YourModuleHere" to the tide SDK directory, and this suggestion here:
[TIdeSDK Python module
import](http://stackoverflow.com/questions/14115173/tidesdk-python-module-
import) but with no success. The module I'm trying to use is
<https://github.com/burnash/gspread>
Any ideas? Thanks...
Answer: In current version of TideSDK, loading custom python modules is not
supported.It loads default set of Python modules compiled within the SDK.
|
PyQT4 how to using def from others model
Question: This code works:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), self.strona)
def strona(self):
self.ui.webView.setUrl(QtCore.QUrl("http://plemiona.pl"))
but this
funkcje.py
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow
def strona():
self.ui.webView.setUrl(QtCore.QUrl("http://xxxx.pl"))
import sys, time, funkcje
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), funkcje.strona)
doesn't work...
Traceback (most recent call last):
File "C:\Python33\liczbapierwsza\TribalWarsBot\funkcje.py", line 5, in przejdz_na_strone_plemion
QtGui.QWidget.__init__(self, parent)
NameError: global name 'self' is not defined
how to import function from funkcje.py and use in e.x run.py
Answer: `strona` needs to have access to the class instance, self. I'm not sure how
you would go about passing the `self` parameter using Qt, but you can always
write a wrapper function as part of your class that calls `strona` and passes
the self parameter. Or import types and add `types.MethodType(funkcje.strona,
self, MyForm)` to the class constructor(`__init__`). That adds funkcje.strona
to the class. Note that the latter is untested by me.
**EDIT:** Here is what to do:
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
types.MethodType(strona, self, MyForm)
QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), strona)
Note: This is untested.
|
python, module object is not callable, calling method in another file
Question: I have a fair background in java, trying to learn python. I'm running into a
problem understanding how to access methods from other classes when they're in
different files. I keep getting module object is not callable.
I made a simple function to find the largest and smallest integer in a list in
one file, and want to access those functions in another class in another file.
Any help is appreciated, thanks.
class findTheRange():
def findLargest(self, _list):
candidate = _list[0]
for i in _list:
if i > candidate:
candidate = i
return candidate
def findSmallest(self, _list):
candidate = _list[0]
for i in _list:
if i < candidate:
candidate = i
return candidate
* * *
import random
import findTheRange
class Driver():
numberOne = random.randint(0, 100)
numberTwo = random.randint(0,100)
numberThree = random.randint(0,100)
numberFour = random.randint(0,100)
numberFive = random.randint(0,100)
randomList = [numberOne, numberTwo, numberThree, numberFour, numberFive]
operator = findTheRange()
largestInList = findTheRange.findLargest(operator, randomList)
smallestInList = findTheRange.findSmallest(operator, randomList)
print(largestInList, 'is the largest number in the list', smallestInList, 'is the smallest number in the list' )
Answer: The problem is in the `import` line. you are importing a _module_ , not a
class. assuming your file is named `other_file.py` (unlike java, again, there
is no rule of "one class, one file"):
from other_file import findTheRange
if your file is named findTheRange too, following java's convenions, then you
should write
from findTheRange import findTheRange
you can also import it just like you did with `random`:
import findTheRange
operator = findTheRange.findTheRange()
* * *
Some other comments:
a) @Daniel Roseman is right. You do not need classes here at all. Python
encourages procedural programming (when it fits, of course)
b) You can build the list directly:
randomList = [random.randint(0, 100) for i in range(5)]
c) You can call methods in the same way you do in java:
largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)
d) You can use built in function, and the huge python library:
largestInList = max(randomList)
smallestInList = min(randomList)
e) If you still want to use a class, and you don't need `self`, you can use
`@staticmethod`:
class findTheRange():
@staticmethod
def findLargest(_list):
#stuff...
|
heroku PostGIS syncdb error
Question: I am having trouble getting a simple GeoDjango app running on heroku. I have
created the postgis extension for my database but I am not able to run syncdb
without getting the following error:
from django.contrib.gis.geometry.backend import Geometry
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/gis/geometry/backend/__init__.py", line 14, in <module>
'"%s".' % geom_backend)
django.core.exceptions.ImproperlyConfigured: Could not import user-defined GEOMETRY_BACKEND "geos".
Any ideas what I am doing wrong? Also does anyone know of a tutorial for
getting a simple geodjango project running on heroku? Thanks for your help
Answer: I ran into this same issue and Joe is correct, you are missing a buildpack.
What I did differently was include both the heroku-geo-buildpack and the
heroku-buildpack-python. Both can be included by using the heroku-buildpack-
multi and adding a ".buildpacks" file to your home directory in which to
include the other buildpacks.
<https://github.com/ddollar/heroku-buildpack-multi>
So set buildpack-multi as your buildpack and add a .buildpacks file in your
project base directory:
$ heroku config:set BUILDPACK_URL=https://github.com/ddollar/heroku-buildpack-multi.git
$ touch .buildpacks
# .buildpacks
https://github.com/cyberdelia/heroku-geo-buildpack.git#1.0
https://github.com/heroku/heroku-buildpack-python
When you push this, Heroku will install the software packages required to run
python (python, pip, etc), along with the software packages required to run
postgis (geos, proj and gdal).
I gave heroku-buildpack-geodjango a try but I believe it might be out of date
(hasn't been updated in a year).
|
Python data scraping with Scrapy
Question: I want to scrape data from a website which has TextFields, Buttons etc.. and
my requirement is to fill the text fields and submit the form to get the
results and then scrape the data points from results page.
I want to know that does Scrapy has this feature or If anyone can recommend a
library in Python to accomplish this task?
(edited)
I want to scrape the data from the following website:
<http://a836-acris.nyc.gov/DS/DocumentSearch/DocumentType>
My requirement is to select the values from ComboBoxes and hit the search
button and scrape the data points from the result page.
P.S. I'm using selenium Firefox driver to scrape data from some other website
but that solution is not good because selenium Firefox driver is dependent on
FireFox's EXE i.e Firefox must be installed before running the scraper.
Selenium Firefox driver is consuming around 100MB memory for one instance and
my requirement is to run a lot of instances at a time to make the scraping
process quick so there is memory limitation as well.
Firefox crashes sometimes during the execution of scraper, don't know why.
Also I need window less scraping which is not possible in case of Selenium
Firefox driver.
My ultimate goal is to run the scrapers on Heroku and I have Linux environment
over there so selenium Firefox driver won't work on Heroku. Thanks
Answer: Basically, you have plenty of tools to choose from:
* [scrapy](http://scrapy.org/)
* [beautifulsoup](https://pypi.python.org/pypi/BeautifulSoup/)
* [lxml](http://lxml.de/)
* [mechanize](http://wwwsearch.sourceforge.net/mechanize/)
* [requests](http://docs.python-requests.org/en/latest/) (and [grequests](https://github.com/kennethreitz/grequests))
* [selenium](https://pypi.python.org/pypi/selenium)
* [ghost.py](http://jeanphix.me/Ghost.py/)
These tools have different purposes but they can be mixed together depending
on the task.
Scrapy is a powerful and very smart tool for crawling web-sites, extracting
data. But, when it comes to manipulating the page: clicking buttons, filling
forms - it becomes more complicated:
* sometimes, it's easy to simulate filling/submitting forms by making underlying form action directly in scrapy
* sometimes, you have to use other tools to help scrapy - like mechanize or selenium
If you make your question more specific, it'll help to understand what kind of
tools you should use or choose from.
Take a look at an example of interesting scrapy&selenium mix. Here, selenium
task is to click the button and provide data for scrapy items:
import time
from scrapy.item import Item, Field
from selenium import webdriver
from scrapy.spider import BaseSpider
class ElyseAvenueItem(Item):
name = Field()
class ElyseAvenueSpider(BaseSpider):
name = "elyse"
allowed_domains = ["ehealthinsurance.com"]
start_urls = [
'http://www.ehealthinsurance.com/individual-family-health-insurance?action=changeCensus&census.zipCode=48341&census.primary.gender=MALE&census.requestEffectiveDate=06/01/2013&census.primary.month=12&census.primary.day=01&census.primary.year=1971']
def __init__(self):
self.driver = webdriver.Firefox()
def parse(self, response):
self.driver.get(response.url)
el = self.driver.find_element_by_xpath("//input[contains(@class,'btn go-btn')]")
if el:
el.click()
time.sleep(10)
plans = self.driver.find_elements_by_class_name("plan-info")
for plan in plans:
item = ElyseAvenueItem()
item['name'] = plan.find_element_by_class_name('primary').text
yield item
self.driver.close()
UPDATE:
Here's an example on how to use scrapy in your case:
from scrapy.http import FormRequest
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
class AcrisItem(Item):
borough = Field()
block = Field()
doc_type_name = Field()
class AcrisSpider(BaseSpider):
name = "acris"
allowed_domains = ["a836-acris.nyc.gov"]
start_urls = ['http://a836-acris.nyc.gov/DS/DocumentSearch/DocumentType']
def parse(self, response):
hxs = HtmlXPathSelector(response)
document_classes = hxs.select('//select[@name="combox_doc_doctype"]/option')
form_token = hxs.select('//input[@name="__RequestVerificationToken"]/@value').extract()[0]
for document_class in document_classes:
if document_class:
doc_type = document_class.select('.//@value').extract()[0]
doc_type_name = document_class.select('.//text()').extract()[0]
formdata = {'__RequestVerificationToken': form_token,
'hid_selectdate': '7',
'hid_doctype': doc_type,
'hid_doctype_name': doc_type_name,
'hid_max_rows': '10',
'hid_ISIntranet': 'N',
'hid_SearchType': 'DOCTYPE',
'hid_page': '1',
'hid_borough': '0',
'hid_borough_name': 'ALL BOROUGHS',
'hid_ReqID': '',
'hid_sort': '',
'hid_datefromm': '',
'hid_datefromd': '',
'hid_datefromy': '',
'hid_datetom': '',
'hid_datetod': '',
'hid_datetoy': '', }
yield FormRequest(url="http://a836-acris.nyc.gov/DS/DocumentSearch/DocumentTypeResult",
method="POST",
formdata=formdata,
callback=self.parse_page,
meta={'doc_type_name': doc_type_name})
def parse_page(self, response):
hxs = HtmlXPathSelector(response)
rows = hxs.select('//form[@name="DATA"]/table/tbody/tr[2]/td/table/tr')
for row in rows:
item = AcrisItem()
borough = row.select('.//td[2]/div/font/text()').extract()
block = row.select('.//td[3]/div/font/text()').extract()
if borough and block:
item['borough'] = borough[0]
item['block'] = block[0]
item['doc_type_name'] = response.meta['doc_type_name']
yield item
Save it in `spider.py` and run via `scrapy runspider spider.py -o output.json`
and in `output.json` you will see:
{"doc_type_name": "CONDEMNATION PROCEEDINGS ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CERTIFICATE OF REDUCTION ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "COLLATERAL MORTGAGE ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CERTIFIED COPY OF WILL ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CONFIRMATORY DEED ", "borough": "Borough", "block": "Block"}
{"doc_type_name": "CERT NONATTCHMENT FED TAX LIEN ", "borough": "Borough", "block": "Block"}
...
Hope that helps.
|
Raise an exception at import if conditions not met
Question: I have a module that depends on some system settings. For example, to work
properly it needs to have an environment variable FOO set. I would like the
module to raise an Exception if this condition is not met at import time.
# mymodule.py
if 'FOO' not in sys.environ:
raise SomeException('ensure that FOO is provided')
I would like to know:
1. Is it the best practice to check those conditions at import time, or maybe it would be better to do it later (when)
2. What type of exception should I raise? Should it be my own `class MyModuleImportError(Exception)` or maybe some built-in exceptions are more suitable and commonly used? One candidate would be [ImportError](http://docs.python.org/2/library/exceptions.html#exceptions.ImportError), but it seems to be reserved for situation when python _"fails to find the module definition"_
Answer: Is this what you are looking for?
>>> import os
>>> if not os.getenv('FOO', False):
raise OSError('FOO not in envs')
* * *
1. Yes, you should check these kind of things at the start of your code. Else there is no reason for it to continue running.
2. an [OSError](http://docs.python.org/2/library/exceptions.html#exceptions.OSError) (as above)
|
How to properly treat feature branches and package interdependencies?
Question: While trying to stick to the branching model from
[http://nvie.com/posts/a-successful-git-branching-model
](http://nvie.com/posts/a-successful-git-
branching-model)
, i.e. using feature branches and merging them back into a develop-branch, I
sometimes encounter the following situation:
Feature `base` (which is both a feature branch and a Python package), is
considered complete and merged into `develop`. Now a feature (=branch&package)
`stuff`, which requires `base`, is branched off and while developing that I
realize that `stuff` needs some modifications/enhancements in `base` that
should have been there from the very beginning. So in which branch should I
modify the package `base`?
* Doing this in the branch `stuff` seems wrong since the modifications of `base` should become part of `dev` no matter when (and if) `stuff` is merged back.
* (Re)branching to `base`, modifying, merging into both `develop` and `stuff` will on the other hand create many merges and I'm not sure whether it is good practice to merge _into_ a feature branch. Especially if it's only a minor yet important modification
* And committing twice (via `git cherry-pick`) also doesn't feel right.
* Turning `base` into a `git submodule` sounds like overkill
* Rebasing `stuff` onto an updated `develop` will make history look nicer, but causes the usual problems should others have pulled the original branch `stuff` \- not a problem in my single-developer case, but the mere possibility of this problem suggests I'm doing something more fundamentally wrong...
Answer: As per <https://www.kernel.org/pub/software/scm/git/docs/gitworkflows.html>'s
"Rule: Topic branches", the recommendation seems to be
> * If you find you need new features from the branch other to continue
> working on your topic, merge other to topic. (However, do not do this "just
> habitually", see below.)
>
where "below" reads
> # Rule: Merge to downstream only at well-defined points
>
>> Do not merge to downstream except with a good reason: upstream API changes
affect your branch; your branch no longer merges to upstream cleanly; etc.
>
> Otherwise, the topic that was merged to suddenly contains more than a single
> (well-separated) change. The many resulting small merges will greatly
> clutter up history. Anyone who later investigates the history of a file will
> have to find out whether that merge affected the topic in development. An
> upstream might even inadvertently be merged into a "more stable" branch. And
> so on.
In summary, that would mean "merge `base` into `stuff`
[iff](https://en.wikipedia.org/wiki/If_and_only_if "if and only if")
necessary, but never merge `develop` into `stuff` (since it probably contains
other features irrelevant to `stuff`)"
|
which numbers in list 2 are bigger and smaller than each number in list 1
Question: i am using python. i have two lists, list 1 is 7000 integers long, list 2 is
25000 integers. i want to go through each number in list 1 and find the
closest number in list 2 that is bigger and the closest number that is smaller
than each number in list 1, and then calculate the difference between these
two numbers in list 2. So far I have:
for i in list1:
for j in list 2:
if list2[j]<list1[i]:
a = max(list2)
elif list2[j]>list1[i]:
b = min(list2)
interval = b-a
this doesn't seem to work. i want to find the explicit numbers in list 2 that
are less than a specific number in list 1 and know the maximum, and then find
out the smallest number in list 2 that is bigger than the number in list 1.
does anyone have any ideas? thanks
Answer: You can use the `bisect` module, worst case complexity `O(N * logN)`:
import bisect
lis1 = [4, 20, 26, 27, 30, 53, 57, 76, 89, 101]
lis2 = [17, 21, 40, 49, 53, 53, 53, 53, 70, 80, 81, 95, 99] #this must be sorted
#use lis2.sort() in case lis2 is not sorted
for x in lis1:
#returns the index where x can be placed in lis2, keeping lis2 sorted
ind=bisect.bisect(lis2,x)
if not (x >= lis2[-1] or x <= lis2[0]):
sm, bi = lis2[ind-1], lis2[ind]
if sm == x:
""" To handle the case when an item present in lis1 is
repeated multiple times in lis2, for eg 53 in this case"""
ind -= 1
while lis2[ind] == x:
ind -= 1
sm = lis2[ind]
print "{} <= {} <= {}".format(sm ,x, bi)
**output:**
17 <= 20 <= 21
21 <= 26 <= 40
21 <= 27 <= 40
21 <= 30 <= 40
49 <= 53 <= 70
53 <= 57 <= 70
70 <= 76 <= 80
81 <= 89 <= 95
Though this will not output anything for `4` and `101`, as 4 is smaller than
any element in lis2 and 101 is greater than any element in lis2. But that can
be fixed if required.
|
How can you specify a default value, using a function, in a gimp python plugin?
Question: I am trying to get gimp to use a reasonable default path in a "save as"
plugin, and to do that I need to be able to specify the default with the
return value of a function (I believe).
Currently, my code is something like:
def do_the_foo(image, __unused_drawable, directory):
# ... do something
register(
"python_fu_something",
"Blah de blah",
"Blah de blah",
"Blah de blah",
"Blah de blah",
"2013",
"<Image>/File/Save as blah...",
"*",
[
(PF_DIRNAME, "directory", "Directory to save files to", "/")
],
[],
do_the_foo
)
Naturally this means that the dialog pops up with "/" as the default
directory. That's not ideal. I'd like it to start with the path to the
currently loaded image if known and then fall back to "/" if the currently
loaded image has no path (not saved, whatever).
But to get there I need to know how to replace "/" with a function. I've tried
doing just that (create a function, reference it in the PF_DIRNAME line) but
no joy (and no error message, either).
Answer: i didn't test it, but maybe...
import os
[...]
(PF_DIRNAME, "directory", "Directory to save files to", os.curdir)
or something like that:
(PF_DIRNAME, "directory", "Directory to save files to", os.path.realpath(os.curdir))
|
Use Multiple DBs With One Redis Lua Script?
Question: Is it possible to have one Redis Lua script hit more than one database? I
currently have information of one type in DB 0 and information of another type
in DB 1. My normal workflow is doing updates on DB 1 based on an API call
along with meta information from DB 0. I'd love to do everything in one Lua
script, but can't figure out how to hit multiple dbs. I'm doing this in Python
using redis-py:
lua_script(keys=some_keys,
args=some_args,
client=some_client)
Since the client implies a specific db, I'm stuck. Ideas?
Answer: It is usually a wrong idea to put related data in different Redis databases.
There is almost no benefit compared to defining namespaces by key naming
conventions (no extra granularity regarding security, persistence, expiration
management, etc ...). And a major drawback is the clients have to manually
handle the selection of the correct database, which is error prone for clients
targeting multiple databases at the same time.
Now, if you still want to use multiple databases, there is a way to make it
work with redis-py and Lua scripting.
redis-py does not define a wrapper for the
[SELECT](http://redis.io/commands/select) command (normally used to switch the
current database), because of the underlying thread-safe connection pool
implementation. But nothing prevents you to call SELECT from a Lua script.
Consider the following example:
$ redis-cli
SELECT 0
SET mykey db0
SELECT 1
SET mykey db1
The following script displays the value of mykey in the 2 databases from the
same client connection.
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)
lua1 = """
redis.call("select", ARGV[1])
return redis.call("get",KEYS[1])
"""
script1 = r.register_script(lua1)
lua2 = """
redis.call("select", ARGV[1])
local ret = redis.call("get",KEYS[1])
redis.call("select", ARGV[2])
return ret
"""
script2 = r.register_script(lua2)
print r.get("mykey")
print script2( keys=["mykey"], args = [1,0] )
print r.get("mykey"), "ok"
print
print r.get("mykey")
print script1( keys=["mykey"], args = [1] )
print r.get("mykey"), "misleading !!!"
Script lua1 is naive: it just selects a given database before returning the
value. Its usage is misleading, because after its execution, the current
database associated to the connection has changed. Don't do this.
Script lua2 is much better. It takes the target database and the current
database as parameters. It makes sure that the current database is reactivated
before the end of the script, so that next command applied on the connection
still run in the correct database. Unfortunately, there is no command to guess
the current database in the Lua script, so the client has to provide it
systematically. Please note the Lua script must reset the current database at
the end whatever happens (even in case of previous error), so it makes complex
scripts cumbersome and awkward.
|
Matching Regex in Python
Question: I wanted to match a certain pattern to a few strings with a one regex line (if
possible):
blah blah (1023 mega lbs) blah blah 1245 tons
blah 1023 kilo tons blah blah 1034 metric tons
blah 1023 feet 345 blah
$100 is a lot of money
I want to match numbers (first occurance in the line, for example) 1023 and
its units (lbs, tons and feet) that may follow it after another word and store
this as another string. However, I have to be careful of $100, because it's
not a unit of measurement that I am concerned with and also any numbers that
may follow the first sequence in that line.
My current approach has many nested `if statements` for example for the first
line I have (not working): `\d*\s(.*)\s\w+` Is there a better way to do this?
Answer:
import re
with open("input") as f:
for line in f:
mo=re.match(r'[^\d]*(\d+).*?(tons|feet|lbs)', line)
if mo: print mo.group(1), mo.group(2)
**Output**
1023 lbs
1023 tons
1023 feet
Also, if you have a line like `$100 money is too much for 100 lbs`, you can
use this:
import re
with open("input") as f:
for line in f:
mo=re.match(r'.*?(?<![$\d])(\d+).*?(tons|feet|lbs)', line)
if mo: print mo.group(1), mo.group(2)
And to match kilo, mega stuff:
import re
with open("input") as f:
for line in f:
mo=re.match(r'.*?(\d+).*?(mega|kilo|metric|) (tons|feet|lbs)', line)
if mo: print mo.group(1), mo.group(2), mo.group(3)
**Output**
1023 mega lbs
1023 kilo tons
1023 feet
100 lbs
It is possible to store these units and modifiers in lists and join them with
`|` to create a regex on the fly.
An example that matches all possible unit modifiers:
import re
with open("input") as f:
for line in f:
mo=re.match(r'[^\d]*(\d+).*?(\S*)\s*(tons|feet|lbs)', line)
if mo: print "'{}' '{}' '{}'".format(mo.group(1), mo.group(2),
mo.group(3))
**Output**
'1023' 'mega' 'lbs'
'1023' 'kilo' 'tons'
'1023' '' 'feet'
|
Installed new version of python, Now I can't use the libraries I've installed for the older version in Mac
Question: I am using an older version of **Python 2.7.3** , but I realize that it is a
32 bit version and I needed a **64 bit** version to be able to use `MySQLdb`.
Also, I have other libraries that I have downloaded for Python 2.7.3. Now my
problem is, none of those libraries can be imported to my newly installed
version of **Python 2.7.5**. Just wondering if there is a way for both
versions to share libraries.
When I tried installing again `MySQLdb`, it wouldn't let me because it's
already installed, but under Python 2.7.3. Any solution?
Answer: > Just wondering if there is a way were both version can share libraries.
While it is possible share pure-Python modules between two different
installations of Python, at least if they have the same minor version, you
generally cannot share C extension modules like `MySQLdb`. And you
_definitely_ cannot use a 32-bit build of a module with a 64-bit Python.
* * *
> And When I tried installing again MySQLdb, it won't let me because it's
> already installed, but under 2.7.3.
There are two possible problems here.
First, you may just be using the wrong Python to do the installation. If you
use the 32-bit Python 2.7.3 to run `python setup.py install`, or the
`easy_install` or `pip` from that copy of Python, it will install into your
2.7.3 site-packages. This one is easy to fix—just use the 64-bit Python 2.7.5,
or its `easy_install` or `pip`.
More seriously, you may have both installations pointing at the same site-
packages directory and interfering with each other. This one is pretty much
impossible to fix; you're not going to make it work.
* * *
More generally, it's difficult to have two Python installations with the same
X.Y minor version on the same machine, and you really shouldn't try to do it
unless you have a very good reason to do so. A much better idea is to
completely uninstall both Pythons, including their site-packages, then do a
clean install of 2.7.5, then reinstall all of your libraries.
(Also, note that if you're using OS X 10.7 or higher, you already have a
64-bit Python 2.7.2 pre-installed by Apple, and you can't get rid of it, and
it can also cause similar problems for you.)
|
Tkinter - Text widget shrinks when Scrollbar is added
Question: I'm working on the GUI for a simple quiz app using Tkinter in Python 2.7. Thus
far, I have begun to set up my frame. I've put a scrollbar inside of a Text
widget named `results_txtbx` to scroll up and down a list noting the player's
performance on each question. I've been using `grid` since it's easier for me
to manage.
from Tkinter import *
class Q_and_A:
def __init__(self, master):
frame = Frame(master)
Label(master).grid(row = 4)
results_txtbx = Text(master)
results_scrbr = Scrollbar(results_txtbx)
results_scrbr.grid(sticky = NS + E)
results_txtbx.config(width = 20, height = 4, wrap = NONE, yscrollcommand = results_scrbr.set)
results_txtbx.grid(row = 3, column = 1, padx = 12, sticky = W)
root = Tk()
root.wm_title("Question and Answer")
root.resizable(0, 0)
app = Q_and_A(root)
root.mainloop()
What happens is that when it runs, `results_txtbx` resizes to fit the
scrollbar. Is there any way to make it keep its original size using `grid`?
Answer: You don't want to use a text widget as the master for a scrollbar. Like any
other widget, if you pack or grid the scrollbar in the text widget, the text
widget will shrink or expand to fit the scrollbar. That is the crux of your
problem.
Instead, create a separate frame (which you're already doing), and use that
frame as the parent for both the text widget and the scrollbars. If you want
the appearance that the scrollbars are inside, set the borderwidth of the text
widget to zero, and then give the containing frame a small border.
As a final usability hint, I recommend _not_ making the window non-resizable.
Your users probably know better what size of window they want than you do.
Don't take that control away from your users.
Here's (roughly) how I would implement your code:
* I would use `import Tkinter as tk` rather than `from Tkinter import *` since global imports are generally a bad idea.
* I would make `Q_and_A` a subclass of `tk.Frame` so that it can be treated as a widget.
* I would make the whole window resizable
* I would separate widget creation from widget layout, so all my layout options are in one place. This makes it easier to write and maintain, IMO.
* As mentioned in my answer, I would put the text and scrollbar widgets inside a frame
Here's the final result:
import Tkinter as tk
class Q_and_A(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master, borderwidth=1, relief="sunken")
self.label = tk.Label(self)
self.results_txtbx = tk.Text(self, width=20, height=4, wrap="none",
borderwidth=0, highlightthickness=0)
self.results_scrbr = tk.Scrollbar(self, orient="vertical",
command=self.results_txtbx.yview)
self.results_txtbx.configure(yscrollcommand=self.results_scrbr.set)
self.label.grid(row=1, columnspan=2)
self.results_scrbr.grid(row=0, column=1, sticky="ns")
self.results_txtbx.grid(row=0, column=0, sticky="nsew")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
root = tk.Tk()
root.wm_title("Question And Answer")
app = Q_and_A(root)
app.pack(side="top", fill="both", expand=True)
root.mainloop()
|
Python: compare one list's index to another, append second list value to first list
Question: I have a .csv file as follows (snippet).
Country,Year,GDP ($US),Population
Angola,2002,11431738368,10760510
Angola,2005,32810672128,11706954
Antigua and Barbuda,2002,714677760,67448
Antigua and Barbuda,2005,875751360,68722
Argentina,2002,1.02E+11,38331121
Argentina,2005,1.83E+11,39537943
Armenia,2002,2376335104,3013818
Armenia,2005,4902779392,2982904
...
I need to find the five lowest GDP/Pop countries for 2002, then find their
corresponding GDP/Pop values in 2005, then compute the difference and the
percent difference. There are blanks for either GDP or Population values for
some records, which I omit.
So far I used
import csv
import operator
data = open('file.csv')
read_data = csv.reader(data)
thisthing = []
for line in read_data:
#find 2002 GDP/Pop, omit blanks, append to list
if line[7] == '2002' and line[8] != ' ' and line[9] != ' ':
thisthing.append([line[0], (float(line[8])/(int(line[9])))])
thisthing.sort(key=operator.itemgetter(1))
This produces a list which print line by line as follows (Country, GDP/Pop):
['Burma (Myanmar)', 69.07171351277908]
['Burundi', 89.45864552423431]
['Congo (Dem. Rep.)', 99.23033109735835]
['Ethiopia', 109.33326343550823]
['Eritrea', 142.8576737907048]
['Guinea-Bissau', 151.110429668747]
['Afghanistan', 159.7524117568956]
['Malawi', 159.7614709537829]
['Sierra Leone', 174.6506490278577]
I want to now iterate back through 'read_data', using the country name in
'thisthing' as a conditional along with my blank prevention conditional
and line[8] != ' ' and line[9] != ' ':
to select and append the 2005 GDP/Pop to 'thisthing'
I have no idea where to begin doing that, and I have been stuck here for about
a week now...any help would be most appreciated.
Answer: try this!!
import csv
import operator
data = open('file.csv') read_data = csv.reader(data)
data_2002 = {}
data_2005 = {}
thisthing = [["country", "2002%", "2005%"]]
for line in read_data:
try:
gdp = float(line[8])/(int(line[9]))
if line[7] == '2002' and line[8] != ' ' and line[9] != ' ':
data_2002[line[0]] = gdp
elif line[7] == '2005' and line[8] != ' ' and line[9] != ' ':
data_2002[line[0]] = gdp
except KeyError:
print line[0]
continue
for country in data_2002:
thisthing.append([country, data_2002[country], data_2005[country]])
print thisthing
|
Test with imperative xfail in py.test always reports as xfail even if the passes
Question: I always thought that imperative and declarative usage of xfail/skip in
py.test should work in the same way. In the meantime I've noticed that if I
write a test that contains an imperative skip the result of the test will
always be "xfail" even it the test passes.
Here's some code:
import pytest
def test_should_fail():
pytest.xfail("reason")
@pytest.mark.xfail(reason="reason")
def test_should_fail_2():
assert 1
Running these tests will always result in:
============================= test session starts ==============================
platform win32 -- Python 2.7.3 -- pytest-2.3.5 -- C:\Python27\python.exe
collecting ... collected 2 items
test_xfail.py:3: test_should_fail xfail
test_xfail.py:6: test_should_fail_2 XPASS
===================== 1 xfailed, 1 xpassed in 0.02 seconds =====================
If I understand correctly what is written in the [user
manual](http://pytest.org/latest/skipping.html), both test should be
"XPASS'ed".
Is this a bug in py.test or am I getting something wrong?
Answer: When using the `pytest.xfail()` helper function you are effectively raising an
exception in the test function. Only when you are using the marker it is
possible for py.test to execute the test fully and give you an XPASS.
|
matplotlib: ways of drawing a CDF
Question: In `python`, with `matplotlib`, I have to draw **2 CDF curves** on the same
plot: one for data A, one for data B.
If I were to decide the "**binning** " myself, I would do the following and
take 100 histograms based on data A. (in my case, A is always at most 50% of
the size of B)
import numpy as np
import matplotlib
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.grid(True)
a = 0
nhist = 100
b = np.max(samplesFromA)
c = b-a
d = float(c) / float(nhist) #size of each bin
# tmp will contain a list of bins: [a, a+d, a+2*d, a+3*d, ... b]
tmp = [a]
for i in range(nhist):
if i == a:
continue
else:
tmp.append(tmp[i-1] + d)
# CDF of A
ax.hist(samplesFromA, bins=tmp, cumulative=True, normed=True,
color='red', histtype='step', linewidth=2.0,
label='samples A')
# CDF of B
plt.hist(samplesFromB, bins=tmp, cumulative=True, normed=True,
color='blue', alpha=0.5, histtype='step', linewidth=1.0,
label='samples B')
Here is the result (I cropped out all the non-relevant information): 
Recently I've found out about `sm.distributions.ECDF`, which I wanted to
compare to my previous implementation. Basically, I will just call the
following function on my data (and decide elsewhere the the range of the
rightmost bin), **without computing any bins** :
def drawCDF(ax, aSample):
ecdf = sm.distributions.ECDF(aSample)
x = np.linspace(min(aSample), max(aSample))
y = ecdf(x)
ax.step(x, y)
return ax
Here is the result, with the same data (again, I manually cropped out non-
relevant text): 
It turns out that this last example **merges too many bins** together and the
result isn't a very well fine-grained CDF curve. What exactly happens behind
the scenes here?
Sample A (in red) contains **70 samples** , while sample B (in blue) contains
**15 000**!
Answer: I suggest you read the
[source](https://github.com/statsmodels/statsmodels/blob/master/statsmodels/distributions/empirical_distribution.py#L108).
if you want evenly spaced bins:
x = np.linspace(min(aSample),
max(aSample),
int((max(aSample) - min(aSample)) / step))
[`np.arange`
doc](http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html)
|
How to do the following operation in python in tricky way?
Question: I have a list of tuples as follows
[(1,4),(3,5),(2,9),(6,23),(3,21),(2,66),(5,20),(1,33),(3,55),(1,8)]
Now I need something like this
1. In the above list, each element is a tuple and the first item in a tuple is an index and the second item is a value.
2. We need to multiply all the tuple values whose indices are equal and then add all the multiplication result for all indices.
3. If there is only once tuple with certain index, we have to make the multiplication result zero for that. That means that tuple does not contribute to the final sum.
I would be so much obliged if some one can help me. I am new in python so
finding it difficult.
Answer: Here's one way to do it. Use `itertools.groupby` to create groups
corresponding to each index, multiply and add
from operator import itemgetter, mul
from itertools import groupby
z = [(1,4),(3,5),(2,9),(6,23),(3,21),(2,66),(5,20),(1,33),(3,55),(1,8)]
z = sorted(z, key=itemgetter(0))
z = groupby(z, key=itemgetter(0))
z = ((key, list(value for (key, value) in groups)) for (key, groups) in z)
z = ((key, reduce(mul, values, 1)) for (key, values) in z if len(values) > 1)
z = sum(value for (key, value) in z)
print z
7425
|
Python: share the command line argument to os.system call
Question: I am new to python. I searched and trying following approach:
I have 3rd party application called "xyz", which takes n argument.
I would like to warp this "xyz" into my module called "abc.py" which required
m arguments.
I would like to read and keep my m arguments and pass remaining n argument to
"xyz"
Note: the number of n argument is huge, so it would best if we dont need to re
state same number of argument in my module and directly pass to "xyz"
Hope it should be possible and I didn't confused.
Thanks for the help.
Answer: Let's say your external program "xyz" is `echo`.
import subprocess
import sys
m = 3 # number of args for abc.py; remainder goes to external program 'echo'
args = sys.argv
abc_args = args[1:m+1]
echo_args = args[m+1:]
cmd = ['echo']
cmd.extend(echo_args)
subprocess.call(cmd)
This results in
$ python abc.py 1 2 3 4 5 6
4 5 6
|
Using code from a dependency in setup.py
Question: I have a little web framework, let's call it Bread, which is used to build
applications like Jam, Marmalade, PeanutButter, and other toppings. Bread both
_builds_ and _serves_ these applications.
I'm trying to figure out how to make the applications' `setup.py`s work, given
the following requirements:
* The apps depend upon Bread, via [setuptool's install_requires](http://peak.telecommunity.com/DevCenter/setuptools#declaring-dependencies)
* To build an application at development time, Bread reads some config and then emits assets (HTML, JS, CSS, images, etc) to the application's `output` directory. In other words, `bread devserver` reads `Jam/bread.yaml` and assembles assets in `Jam/output`, then serves the application (via Flask, but that's not otherwise pertinent).
* In order to build a _deployable_ Jam application, I want to invoke Bread during `python setup.py install` of Jam, to build `Jam/output`. In production, Jam should not need to build anything.
* I've defined a custom `bdist_egg` setup command where `initialize_options` imports Bread, invokes the builder, then sets `self.distribution.data_files` with the appropriate tuples, before calling the base class. (And _that_ was no fun to figure out.)
* Right now, the `bdist_egg` is defined in Jam's `setup.py`. I want to move this and other boilerplate code into `bread.setup`, so that I can reuse it in Marmalade, PeanutButter, etc.
* Potentially, this means that I'm now importing Bread code before Bread has been installed. This will surely arise in a clean install, such as a fresh virtualenv on a build machine.
Can this be done with Distutils / setuptools / Distribute?
Answer: I also asked this question in [Distutils-
SIG](http://mail.python.org/pipermail/distutils-sig/2013-May/020963.html). A
mention there of `setup_requires` led me to
<http://stackoverflow.com/a/12061891/6364>, which gave me the hint I needed:
create a separate `Distribution` object before calling `setup` which defines
the `setup_requires` entries.
Jam's `setup.py` now looks like:
from setuptools import setup, dist
dist.Distribution(dict(setup_requires='Bread'))
from bread.setup_topping import *
setup(
name='Jam',
version='0.2',
long_description=open('README.md').read(),
**topping_setup_options
)
# Remove *.egg left by bootstrapping Bread
cleanup_bread_bootstrap()
* * *
EDIT: a better explanation of what's happening in Jam's `setup.py` is needed:
* The initial `Distribution(setup_requires='Bread')` is using `easy_install` to install Bread and its dependencies in the _current directory_.
* The call to `setup()` triggers the `bdist_egg` below, which uses Bread to build Jam's `output`. Bread is found in the current directory.
* `setup()` later installs Jam, Bread, and all the dependencies, in the correct location.
* The call to `cleanup_bread_bootstrap()` removes all the Eggs that were laid in the current directory by the initial `Distribution`.
* * *
And `bread/setup_topping.py` looks like:
from setuptools.command.bdist_egg import bdist_egg as _bdist_egg
import os, fnmatch, glob, shutil
def recursive_data_files(treeroot, pattern):
results = []
for base, dirs, files in os.walk(treeroot):
goodfiles = fnmatch.filter(files, pattern)
if goodfiles:
results.append((base, [os.path.join(base, f) for f in goodfiles]))
return results
def make_data_files(output='output'):
return (
[('', ['bread.yaml'])]
+ recursive_data_files(output, '*')
)
class bdist_egg(_bdist_egg):
def initialize_options(self):
bake_bread() # build files to './output'
self.distribution.data_files = make_data_files()
_bdist_egg.initialize_options(self)
topping_setup_options = dict(
cmdclass={
'bdist_egg': bdist_egg,
},
install_requires=[
'Bread',
],
zip_safe=False,
)
def cleanup_bread_bootstrap(root='.'):
for f in glob.glob(os.path.join(os.path.abspath(root), '*.egg')):
if os.path.isdir(f):
shutil.rmtree(f) # Egg directory
else:
os.remove(f) # Zipped Egg
|
Python I/O and string matching
Question: I realize this is probably really easy, I want the equivalent of this C code
in Python:
#include <stdio.h>
#include <string.h>
#define BUFFER 200
int main()
{
char buffer[BUFFER];
while (fgets(buffer, BUFFER, stdin))
{
if (strstr(buffer, "BEER"))
printf("Drink up!\n");
}
return 0;
}
I searched on the web, but I think my brain is fried.
Answer: The Pythonic thing to do is a little different:
import fileinput
for line in fileinput.input():
if "BEER" in line:
print("Drink up!")
But that does a whole lot of things your C code doesn't do, like allowing the
user to pass filename arguments to be read in place of stdin as arguments,
etc.
* * *
This is a more direct mapping of your code:
try:
while True:
buffer = input() # or raw_input, for 2.x
if "BEER" in buffer:
print("Drink up!")
except EOFError:
pass
However, it's missing the part where a line more than 300-character line that
includes `"BEER"` in the first 200 characters and then again in the next will
print twice, or a 300-character line that has "BEER" starting at position 198
won't print it at all.
* * *
If that's a problem, you probably want something like this:
import sys
while True:
buffer = sys.stdin.readlines(200)
if not buffer:
break
for line in buffer:
for i in range(0, len(buffer), 200):
if "BEER" in buffer[i*200:i*200+200]:
print("Drink up!")
|
Change string Beautiful Soup
Question: I have a problem writing code in Python and BS4.
Assuming have the next paragraph:
<p id="paragraph">
Here is the paragraph <a href="/" id="url">Here an url</a> the paragraph continues.
</p>
I take the id and use `replace_with` to replace the string (in P and A tag).
But in this case, results in this:
Here is the paragraph the paragraph continues. Here an url
The structure is not respected. What is the correct method?
Add some code:
page = open('file.html')
soupPage = BeautifulSoup(page)
findId = soupPage.find(id='nameOfId')
findId.replace_with('NewString')
Answer: Try this:
from bs4 import BeautifulSoup
page = open('file.html')
soupPage = BeautifulSoup(page)
findId = soupPage.find(id='url')
findId.contents[0].replace_with('NewString')
print soupPage
prints:
<html><body><p id="paragraph">
Here is the paragraph <a href="/" id="url">NewString</a> the paragraph continues.
</p></body></html>
Hope it's what you wanted.
|
how to make python3.3 gui window fixed sizes?
Question: as for the question mentioned, i cant find any code which can fixed the gui
window and positions of all the labels, buttons etc..
import tkinter
import tkinter.messagebox
class Menu:
def __init__(self):
self.main = tkinter.Tk(height = 200, width = 400)
self.position = tkinter.Label(self.main, text = '123',\
bg = 'Purple',\
height = 2, width = 8)
self.position.place(height=50, width= 100)
self.position.pack()
tkinter.mainloop()
gui = Menu()
for this, i can only do the sizing of the label, not the position and the size
of the main window. it gives this error
Traceback (most recent call last):
File "C:\Python33\Saves\Label position.py", line 18, in <module>
gui = Menu()
File "C:\Python33\Saves\Label position.py", line 7, in __init__
self.main = tkinter.Tk(height = 200, width = 400)
TypeError: __init__() got an unexpected keyword argument 'height'
Answer: It looks like you cannot set the width and height of the Tk element in the
constructor. However, you can use the `geometry` method:
self.main = tkinter.Tk()
self.main.geometry("400x200")
|
Python convert a paritcular string to dict
Question: The format of string is like `"a:1 b:2 c:x d:2.13e-5"`, is there some way to
convert it to python dict quickly and simply?
\-------------- edit line --------------
According the great answers, I tried several methods (in ipython):
In [6]: import re
In [7]: %paste
def f1(line):
item_dict = {}
for item in line.split():
kv = item.split(':')
item_dict[kv[0]] = kv[1]
def f2(line):
item_dict = {}
item_pat = re.compile(r'(\w+):(.+)')
for item in line.split():
m_res = item_pat.match(item)
item_dict[m_res.group(1)] = m_res.group(2)
def f3(line):
dict(item.split(':') for item in line.split())
## -- End pasted text --
In [8]: line = 'a:1 b:3243 dsfds:4323llsjdf \t fdsf:3232l'
In [9]: %timeit f1(line)
100000 loops, best of 3: 3.99 us per loop
In [10]: %timeit f2(line)
100000 loops, best of 3: 8.83 us per loop
In [11]: %timeit f3(line)
100000 loops, best of 3: 5.19 us per loop
The first method `f1()` seems faster, but in my application, it still use much
time(about 30% of all) because it's invoked millions of times.
Are there any more effective ways? Or `cython`?
Answer:
>>> s = "a:1 b:2 c:x d:2.13e-5"
>>> dict( p.split(':') for p in s.split(' ') )
{'a': '1', 'c': 'x', 'b': '2', 'd': '2.13e-5'}
This [`split`](http://docs.python.org/2/library/stdtypes.html#str.split)s the
string, first by spaces, to get the key-value pairs (`p`). Then it splits each
pair by ':' to yield each key/value to be added to the dictionary.
Note that no conversion has taken place. All keys/values are still strings. To
do any better than this, you're going to need a somewhat smart function that
will convert any input string into your expected types.
|
How to read JUST filenames of a directory in python and then do the same job for all?
Question: I have a python script which has this line at the very beginning to read from
an input data file:
x,y = genfromtxt('data1.txt').T
Then I proceed and do the processing on x,y (it depends on a fixed parameter
e.g n=5). Finally I generate the output file with this line
with open('output_data1_n{0}.txt'.format(num),'wb') as file:
This gives me output_data1_n5.txt and write the xnew and ynew on it.
Question: I have a directory with many txt files! How can I systematically do
this job for all files in that directory instead of running by hand for each
input file?
It should be like: get the txt files (e.g with os.walk ?) as a string and
replace it to input, then generate the output name including the parameter n.
I appreciate your suggestions.
Answer: Try the [`glob` module](http://docs.python.org/2/library/glob.html).
It lets you get a list of file names in a directory with some wild cards.
Example:
from glob import glob
from os import path
def get_files_in(folder, pattern='*.txt'):
return glob(path.join(folder, pattern))
Usage:
get_files_in('C:/temp') # files in C:/temp that are ending with .txt
get_files_in('C:/temp', '*.xml') # files in C:/temp that are ending with .xml
get_files_in('C:/temp', 'test_*.csv') # files in C:/temp that start with test_ and end in .csv
|
default colorbar for matplotlib
Question: I'd like to change the global default colorbar for all graphics commands in
Python matplotlib. This is similar to [this question about changing the
default colorbar in MATLAB](http://stackoverflow.com/questions/6034903/how-do-
you-set-a-custom-default-colormap-in-matlab). Here [there is already a
pythonic solution](http://stackoverflow.com/questions/10437689/matplotlib-
globally-set-number-of-ticks-x-axis-y-axis-colorbar), but that solution
requires making a plot in order for the change to take effect. Is there a way
to set the default before the first plot is made?
Putting the following in `~/.pythonrc` seems like it ought to work, but it
does not:
import matplotlib.pylab as plt
plt.rcParams['image.cmap'] = plt.cm.bwr
Furthermore, I'd like to set the default to something from the
`colorbrewer2mpl` package, not just a pre-existing matplotlib option.
Answer: One solution that does work is to [customize the matplotlibrc
file](http://matplotlib.org/users/customizing.html)
Find it:
import matplotlib
matplotlib.matplotlib_fname()
Edit it:
image.cmap: bwr
However, this method only lets me select default named colorbars, not, for
example, [ColorBrewer](http://colorbrewer2.org/) colorbars available via the
`colorbrewer2mpl` package.
|
Python Iterative Loop Plot values
Question: I am trying to carry out an iterative calculation in python using a finite
difference method. I found the finite difference method from this:
<http://depa.fquim.unam.mx/amyd/archivero/DiferenciasFinitas3_25332.pdf>
The values that the code calculates are correct. The problem is that it is
only showing the final values. What I want is to extract the values for any
point in the x-direction so that I can plot them, as well as extract the
values at any point in time e.g the values of the points halfway through the
calculations. Is this the right way for doing an iterative calculation? The
code is shown below:
import numpy as np
import scipy as sp
import time
import matplotlib as p
L=0.005
Nx=3
T=5
N1=5
k=0.5
rho=1200
c=1000
a=(k/(rho*c))
x = np.linspace(0, L, Nx+1) # mesh points in space
dx = x[1] - x[0]
t = np.linspace(0, T, N1) # time
dt = t[1] - t[0]
toutside=5
Coefficient = a*dt/dx**2
bi=0.5
ui = sp.zeros(Nx+1)
u = sp.zeros(Nx+1)
for i in range(Nx+1):
ui[i] = 50 # initial values
for n in range(0, N1):
for i in range(0,1):
u[i] = 2*Coefficient*(ui[i+1]+bi*toutside)+(1-2*Coefficient-2*bi*Coefficient)*ui[i]
for i in range(1,Nx):
u[i] = Coefficient*(ui[i+1]+ui[i-1])+(1-2*Coefficient)*ui[i]
for i in range(Nx,Nx+1):
u[i] = 2*Coefficient*(ui[i-1])+(1-2*Coefficient)*ui[i]
ui[:]= u #updates matrix for next loop
print ui
I've modified my code to based on danodonovan answer to:
for n in range(0, N1):
for i in range(0,1):
u[i] = 2*Coefficient*(ui[i+1]+bi*toutside)+(1-2*Coefficient-2*bi*Coefficient)*ui[i]
for i in range(1,Nx):
u[i] = Coefficient*(ui[i+1]+ui[i-1])+(1-2*Coefficient)*ui[i]
for i in range(Nx,Nx+1):
u[i] = 2*Coefficient*(ui[i-1])+(1-2*Coefficient)*ui[i]
ui=u
a=list(ui)
print a
When I try to take the entire list out of the loop, only the final values are
produced. How do I extract the whole list? Is this the right way to do an
iterative calculation using the values of the previous row to calculate the
values of the new row?
Answer: (If I understand your question correctly) Using `matplotlib` you can do
import matplotlib as p
# and after your loop has completed
p.pyplot.plot(range(0, N1), ui, 'o-')
p.pyplot.show()
to get a simple plot of your data `u` against `range(0, N1)`.
I don't know what you expect `ui` to be `ui[:]= u` is an odd thing to be doing
- it sets a copy of `ui` to `u` but you don't retain the copy of `ui` that
`ui[:]` is producing.
_Hint: think about`ui[:]` as being the same as `list(ui)`_
|
Python if/elseif construction as dictionary
Question: In Python I use regularly the following construct:
x = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
y = x[v] if v in x.keys() else None
where v is normally one of the dictionary values, and y gets the value of the
dictionary if the key exists, otherwise None.
I was wondering if this is a desired construct or if it can be enhanced?
x[v] can be values as above, but I also use a similar construct to call a
function depending on the value of v, like:
{'a': self.f1, 'b': self.f2, 'c': self.f3, 'd': self.f4}[v]()
Answer: Normally you'd use
[`dict.get()`](http://docs.python.org/2/library/stdtypes.html#dict.get):
y = x.get(v)
`.get()` takes a default parameter to return if `v` is not present in the
dictionary, but if you omit it `None` is returned.
Even if you were to use an explicit key test, you don't need to use `.keys()`:
y = x[v] if v in x else None
Interestingly enough, the conditional expression option is slightly faster:
>>> [x.get(v) for v in 'acxz'] # demonstration of the test; two hits, two misses
[1, 3, None, None]
>>> timeit.timeit("for v in 'acxz': x.get(v)", 'from __main__ import x')
0.8269917964935303
>>> timeit.timeit("for v in 'acxz': x[v] if v in x else None", 'from __main__ import x')
0.67330002784729
until you avoid the attribute lookup for `.get()`:
>>> timeit.timeit("for v in 'acxz': get(v)", 'from __main__ import x; get = x.get')
0.6585619449615479
so if speed matters, store a reference to the `.get()` method (note the `get =
x.get` assignment).
|
Extracting the extracted with python
Question: I have a zip file containing thousands of mixed .xml and .csv files. I used
the following to extract the zip file:
import zipfile
zip = zipfile.ZipFile(r'c:\my.zip')
zip.extractall(r'c:\output')
Now I need to extract the thousands of individual zip files contained in the
'c:\output' folder. I am planning on concatenating just the .csv files into
one file. Thank you for the help!
Answer: Try this code :
import zipfile , os
zip = zipfile.ZipFile(r'c:/my.zip')
zip.extractall(r'c:/output')
filelist = []
for name in zip.namelist():
filelist.append(name)
zip.close()
for i in filelist:
newzip = zipfile.ZipFile(r'c:/output/'+str(i))
for file in newzip.namelist():
if '.csv' in file :
newzip.extract(file,r'c:/output/')
newzip.close()
os.remove(r'c:/output/'+str(i))
|
Printing error in Python?
Question: I'm new to Python, I've only done programming in Java before recently. I am
writing a basic program in Python to print out the 1000th prime number and
while I did get it to work, for some reason it's also printing out the next 7
numbers unless I use an unnecessary break:
import math
n=2
location =0
while location < 999 :
if location == 998 :
print n
n=n+1
srn = math.sqrt(n)
srn = int(srn)
while srn > 1 :
if n % srn == 0 :
break
elif srn==2 and n%srn != 0 :
location = location+1
srn = srn-1
prints
7919
7920
7921
7922
7923
7924
7925
7926
but
while location < 999 :
if location == 998 :
print n
break
n=n+1
srn = math.sqrt(n)
srn = int(srn)
while srn > 1 :
if n % srn == 0 :
break
elif srn==2 and n%srn != 0 :
location = location+1
srn = srn-1
prints
7919
Can anyone tell me why this is happening? Also when I was trying to fix this,
I found that the shell would only print this once, then if I copied the code,
whether I altered it or not, it wouldn't print anything. I would need to
restart the shell each time I wanted to alter the code.
Answer: In the first case, you are printing until you have found the next prime. It is
continuing in the `while` loop. And since `location == 998` is true, it prints
the numbers. Then when it finds the next prime `location < 999` resolves to
false and the `while` loop is completed.
You need the `break` so that the code leaves the while loop when you found the
prime.
If you don't want to `break` move the print out of the loop and reduce the
while condition by 1.
while location < 998 :
n=n+1
srn = math.sqrt(n)
srn = int(srn)
while srn > 1 :
if n % srn == 0 :
break
elif srn==2 and n%srn != 0 :
location = location+1
srn = srn-1
print n
|
Skip the last row of CSV file when iterating in Python
Question: I am working on a data analysis using a CSV file that I got from a
datawarehouse(Cognos). The CSV file has the last row that sums up all the rows
above, but I do not need this line for my analysis, so I would like to skip
the last row.
I was thinking about adding "if" statement that checks a column name within my
"for" loop like below.
import CSV
with open('COGNOS.csv', "rb") as f, open('New_COGNOS.csv', "wb") as w:
#Open 2 CSV files. One to read and the other to save.
CSV_raw = csv.reader(f)
CSV_new = csv.writer(w)
for row in CSV_raw:
item_num = row[3].split(" ")[0]
row.append(item_num)
if row[0] == "All Materials (By Collection)": break
CSV_new.writerow(row)
However, this looks like wasting a lot of resource. Is there any pythonian way
to skip the last row when iterating through CSV file?
Answer: You can write a generator that'll return everything but the last entry in an
input iterator:
def skip_last(iterator):
prev = next(iterator)
for item in iterator:
yield prev
prev = item
then wrap your `CSV_raw` reader object in that:
for row in skip_last(CSV_raw):
The generator basically takes the first entry, then starts looping and on each
iteration yield the previous entry. When the input iterator is done, there is
still one line left, that is never returned.
A generic version, letting you skip the last `n` elements, would be:
from collections import deque
from itertools import islice
def skip_last_n(iterator, n=1):
it = iter(iterator)
prev = deque(islice(it, n), n)
for item in it:
yield prev.popleft()
prev.append(item)
|
Random String Generation Based on Regular Expression-Python
Question: According to the [this](https://bitbucket.org/leapfrogdevelopment/rstr/)
random strings can be generated importing rstr module.
import rstr
rstr.rstr('ABC')
but when I compile this following error is given?
ImportError: No module named rstr
I'm using python 3.3. What could be the reason?
Answer: You need to download the module and then make sure your python script can find
it.
|
python to exe convert part of the code
Question: Very good, anyone know if I can make exe single piece of code in a script, for
example:
one file (hello.py):
print('hello word')
def exit():
print('good bye')
two file (setup.py):
from distutils.core import setup
import py2exe
import sys
import hello
if len(sys.argv) == 1:
sys.argv.append("py2exe")
sys.argv.append("-q")
options = {
#"bundle_files": 1,
"dll_excludes": ["w9xpopen.exe"] # we don't need this
}
setup(name = "python",
description = "aplicacion python",
version = "1.0",
console = [
{
"script":"hello.exit()",
#"icon_resources": [(0, "res_python.ico")]
}
],
options = {"py2exe": options},
zipfile = None,
)
for a better explanation, I create the exe from the same file, thanks.
Answer: file setup.py :
from distutils.core import setup
import py2exe
import sys
import shell
main = shell.shell()
if len(sys.argv) == 1:
sys.argv.append("py2exe")
sys.argv.append("-q")
options = {
#"bundle_files": 1,
"dll_excludes": ["w9xpopen.exe"] # we don't need this
}
setup(name = "python",
description = "aplicacion python",
version = "1.0",
console = [
{
"script":"main.conexion()",
#"icon_resources": [(0, "res_python.ico")]
}
],
options = {"py2exe": options},
zipfile = None,
)
idle response:
**running py2exe creating C:\Documents and
Settings\francisco\Escritorio\programas python\mis_proyectos\shell
reverse\build creating C:\Documents and
Settings\francisco\Escritorio\programas python\mis_proyectos\shell
reverse\build\bdist.win32 creating C:\Documents and
Settings\francisco\Escritorio\programas python\mis_proyectos\shell
reverse\build\bdist.win32\winexe creating C:\Documents and
Settings\francisco\Escritorio\programas python\mis_proyectos\shell
reverse\build\bdist.win32\winexe\collect-2.7 creating C:\Documents and
Settings\francisco\Escritorio\programas python\mis_proyectos\shell
reverse\build\bdist.win32\winexe\bundle-2.7 creating C:\Documents and
Settings\francisco\Escritorio\programas python\mis_proyectos\shell
reverse\build\bdist.win32\winexe\temp creating C:\Documents and
Settings\francisco\Escritorio\programas python\mis_proyectos\shell
reverse\dist _**searching for required modules**_**
|
How to sort nested lists into seperate lists with unique values in python?
Question: I have two variables:
unique_val = [1,2,3]
nested_list = [['name1',1],['name2',1],['name3',3],['name4',2],['name5',2],['name6',3]]
Basically I want separate lists of the names at each unique value. I struggled
to put together a set of nested for loops to no avail.
Ideally the output would be something like this:
list_1 = ['name1','name2']
list_2 = ['name4','name5']
list_3 = ['name3',name6']
Answer: Creating variables for each item in `unique_val` is not a good idea. Instead
of hard coding everything better use a dict with keys like `list_1` as it'll
handle any number number of variables.
>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> nested_list = [['name1',1],['name2',1],['name3',3],['name4',2],['name5',2],['name6',3]]
>>> unique_val = [1,2,3] #better make this a set to get O(1) lookup
>>> for v,k in nested_list:
if k in unique_val:
dic['list_'+str(k)].append(v)
#now access those lists:
>>> dic['list_1']
['name1', 'name2']
>>> dic['list_2']
['name4', 'name5']
>>> dic['list_3']
['name3', 'name6']
In case you had a 4 in `unique_val` then you may expect `list_4` to be an
empty list, this is easily handled by a `defaultdict`:
>>> dic['list_4']
[]
|
How to dynamically create classes inside a module-level initialize() method in Python
Question: I'm writing a library to talk to a database using SQLAlchemy. I really like
SQLAlchemy's `autoload_with=engine` feature, which can be passed to the
`Table` constructor to grab all of the table's columns without the programmer
having to define them explicitly.
Here's the basic approach for a table named "something":
Base = declarative_base()
engine = create_engine('mysql://user:pass@host/db_name')
table = Table('something', Base.metadata, autoload_with=engine)
class Something(Base):
__table__ = table
However, we have multiple versions of our database (on different hosts) so I
need my engine to be passed in as a parameter at runtime. I sort of hate the
idea of writing something like this in my module, but I'm blanking on a better
approach:
Base = declarative_base()
Something = None # gets defined after initialize() is called
def initialize(engine):
table = Table('something', Base.metadata, autoload_with=engine)
class _Something(Base):
__table__ = table
global Something
Something = _Something
And then client code has to do something nasty like this before using any of
the SQLAlchemy models:
import custom_db_api
engine = create_engine(...)
custom_db_api.initialize(engine)
Is there a better approach to handling this kind of module-initialization by
an outside caller?
Answer: Well, you'll have to find some way to pass the `engine` variable to your
`custom_db_api` module. This might be marginally cleaner...
Base = declarative_base()
class Something(Base):
pass
def initialize(engine):
Something.__table__ = Table('something', Base.metadata, autoload_with=engine)
...or if you can infer the correct engine initialization parameter from some
'global', like `sys.argv`, you could use something like this...
import sys
Base = declarative_base()
if len(sys.argv) > 1 and sys.argv[1] == '--use-alt-db':
engine = create_engine('mysql://user:pass@alt_host/db_name')
else:
engine = create_engine('mysql://user:pass@main_host/db_name')
table = Table('something', Base.metadata, autoload_with=engine)
class Something(Base):
__table__ = table
It kinda depends on how you intend to tell the program which DB to use.
|
Python: Importing from a running instance, or an alternative
Question: I have 2 files, data.py and interpret.py.
data.py:
X = cPickle.load(open("X","r"))
interpret.py:
from data import X
query = raw_input("Enter query")
#do something with query and X
Object X which is very huge. I dumped it using cPickle. interpret.py will be
invoked by another program and because of the way import currently works,
everytime interpret.py is executed, it loads data.py which loads X, and since
X is very big it takes a lot of time.
I want to be able to do something like this.
data.py:
from time import sleep
X = cPickle.load(open("X","r"))
sleep(10**10) #Sleep for eternity
and then run data.py
interpret.py:
from data import X #import from live instance of data.py
#don't load X all over again
query = raw_input("Enter query")
#do something with query and X
How can I do this? If I cannot import from a live instance, is there an
alternative to do what I want to do. I am not communicating very well, please
tell me which parts you don't understand and I will try to clarify further.
Answer: From what I can tell you want to be running a daemon. For instance instead of
importing data from interpret, data would run as a standalone daemon which
interpret would communicate with over something like a socket.
But at this point you've basically written a database, so why not just
translate whatever data you have into some database and just communicate with
a database?
Edit: The problem is that you want the huge object to persist between
processes, but it can't work like that persay. Every time you call intepret, a
new process is spawned which means that there is no access to the object
generated by the previous process. That's why daemons (and databases) exist.
|
Move tkinter label using button command
Question: I am trying to recreate the boardgame monopoly using python and tkinter. I
know how to place a label on a canvas or a frame, but how should I do this
command is being run from another function in the class? I tried it using some
function within the class Board, but then the error rises that the label,
canvas, etc. are not defined as this happens in `__init__(self,parent)`. How
can I solve these errors? Or should I take a different approach to this? Hope
I made my problem clear.
import tkFileDialog
from random import randint
class Board(Frame):
def __init__(self,parent):
##create the board
frame = Frame(parent)
frame.pack()
Frame.__init__(self,parent)
frame2 = Frame(frame)
frame2.pack()
c=Canvas(frame2,width=480,height=480)
c.pack(expand=YES,fill=BOTH)
c.background=PhotoImage(file='Board.gif')
c.create_image(0,0,image=c.background,anchor='nw')
##Add player 1
player1=PhotoImage(file='plane.gif')
label_player1 = Label(c,image=player1)
label_player1.image=player1
label_player1.place(x=430,y=420)
##Add player 2
player2=PhotoImage(file='car.gif')
label_player2 = Label(c,image=player2)
label_player2.image=player2
label_player2.place(x=430,y=450)
button = Button(frame, text="Next turn", command=self.next_turn)
button.pack()
button = Button(frame, text="Roll the dice", command=self.roll)
button.pack()
def roll(self):
number=randint(2,12)
if b==0:
self.place_player_down()
return number
def place_player_down(self):
for i in range(number+1):
h=int(430-i*30)
while h>=0:
player2=PhotoImage(file='car.gif')
label_player2 = Label(c,image=player2)
label_player2.image=player2
label_player2.place(x=h,y=420)
root = Tk()
board = Board(root)
board.pack()
root.mainloop()
Answer: The approach is correct (wrap your Tkinter widgets in a class with the event
handler functions as methods), but you forgot to set the widgets as attributes
of the class using the reference to `self`:
class Board(Frame):
def __init__(self,parent):
# ...
self.c = Canvas(frame2,width=480,height=480)
self.c.pack(expand=YES,fill=BOTH)
# ...
def place_player_down(self):
# Use 'self.c', not just 'c'
I think you want to do something similar with the value `number`, but it that
case I would send it as an argument to `place_player_down`:
def roll(self):
number=randint(2,12)
if b==0:
self.place_player_down(number)
return number # Keep in mind that this value is returned but not used anymore
def place_player_down(self, number):
# Use 'number'
|
Using Python Ctypes to pass struct pointer to a DLL function
Question: I am attempting to access a function in a DLL file using Python ctypes. The
provided function description is below.
Prototype: Picam_ConnectDemoCamera( PicamModel model,
const pichar* serial_number,
PicamCameraID* id )
Description: Virtually connects the software-simulated 'model' with 'serial_number'
and returns the camera id in `_id_`
Notes: `_id_` is optional and can be null
The function references a few variable types defined in the DLL. These
variables are described next
PicamModel
Type: enum
Description: The camera model.
PicamCameraID
Type: Struct
- PicamModel model: _model_ is the camera model
- PicamComputerInterface computer_interface: computer_interface is the method of
communication
- pichar sensor_name [PicamStringSize_SensorName]: sensor_name contains the name of
the sensor in the camera
- pichar serial_number [PicamStringSize_SerialNumber]: serial_number contains the
unique serial number of the camera
Note that'pichar' is defined in one of the provided header files as follows:
typedef char pichar; /* character native to platform
This seems straightforward, but isn't working out for me for some reason.
My understanding is as follows: I pass the function three variables:
1) a `model`, which is really an `enum`. I'm told that python ctypes doesn't
inherently support enums, and so I am passing it an integer, 2, which maps to
a particular model type.
2) a pointer to a serial number (I can make this up: an arbitrary string)
3) A pointer to `PicamCameraID`, a variable type defined within the DLL, based
on the `struct` type
After reading through SO I found a few good starting points, but am still
running out of luck. Here's my best shot so far
def pointer(x):
PointerToType = ctypes.POINTER(type(x))
ptr = ctypes.cast(ctypes.addressof(x), PointerToType)
return ptr
class PicamCameraID(ctypes.Structure):
pass
PicamCameraID._fields_=[("model",ctypes.c_int),
("computer_interface",ctypes.c_int),
("sensor_name",ctypes.c_char_p),
("serial_number",ctypes.c_char_p)]
myid = PicamCameraID()
model = ctypes.c_int(2)
serialnum = ctypes.c_char_p('asdf')
print picam.Picam_ConnectDemoCamera(model, pointer(serialnum), ctypes.byref(myid))
As you can hopefully see, I'm trying to create the variable type that
corresponds to the `PicamCameraID` struct defined in the DLL. My intuition was
to use the `ctypes.pointer` command to reference this when passing the
argument to the function, but I found indications to use `ctypes.byref`
instead [elsewhere](http://stackoverflow.com/questions/10484995/python-ctypes-
passing-in-pointer-and-getting-struct-back).
The code runs without error (returns 0), however, I get varying results when I
try to access the properties of the struct `PicamCameraID`:
`myid.model` returns "2" which is great that's what I specified
`myid.computer_interface` returns "1" which is fine
**BUT** the problem is `myid.serial_number` returns
Traceback (most recent call last): File "<pyshell#28>", line 1, in
<module>
myid.serial_number ValueError: invalid string pointer 0x2820303031207820
and `myid.sensor_name` returns:
Traceback (most recent call last): File "<pyshell#29>", line 1, in
<module>
myid.sensor_name ValueError: invalid string pointer 0x3034333120563245
For some reason these strings aren't being properly populated?
Any ideas would be much appreciated, I am a novice to python ctypes (and c)
Kind regards
Addition June 1 2013
typedef enum PicamStringSize {
PicamStringSize_SensorName = 64,
PicamStringSize_SerialNumber = 64,
PicamStringSize_FirmwareName = 64,
PicamStringSize_FirmwareDetail = 256 } PicamStringSize;
typedef struct PicamCameraID {
PicamModel model;
PicamComputerInterface computer_interface;
pichar sensor_name[PicamStringSize_SensorName];
pichar serial_number[PicamStringSize_SerialNumber];
} PicamCameraID;
Answer: Your definition of PicamCameraID structure is incorrect: `sensor_name` and
`serial_number` are
[arrays](http://docs.python.org/2/library/ctypes.html#ctypes-arrays):
"""
struct PicamCameraID {
PicamModel model;
PicamComputerInterface computer_interface;
pichar sensor_name[PicamStringSize_SensorName];
pichar serial_number[PicamStringSize_SerialNumber];
};
"""
import ctypes as c
PicamStringSize_SensorName = PicamStringSize_SerialNumber = 64
PicamModel = PicamComputerInterface = c.c_int
pichar = c.c_char
class PicamCameraID(c.Structure):
_fields_ = [("model", PicamModel),
("computer_interface", PicamComputerInterface),
("sensor_name", pichar * PicamStringSize_SensorName),
("serial_number", pichar * PicamStringSize_SerialNumber)]
It seems the second argument is just a string, so you don't need to apply
`pointer()` to it. Here's the `ctypes` prototype for
`Picam_ConnectDemoCamera()` function:
"""
Picam_ConnectDemoCamera(PicamModel model, const pichar* serial_number,
PicamCameraID* id)
"""
pichar_p = c.c_char_p # assume '\0'-terminated C strings
Picam_ConnectDemoCamera.argtypes = [PicamModel, pichar_p,
c.POINTER(PicamCameraID)]
Picam_ConnectDemoCamera.restype = c.c_int # assume it returns C int
To call it:
picam_id = PicamCameraID()
rc = Picam_ConnectDemoCamera(2, "serial number here", c.byref(picam_id))
print(rc)
print(picam_id.sensor_name.value) # C string
print(picam_id.sensor_name.raw) # raw memory
|
SQLite Data Change Notification Callbacks in Python or Bash or CLI
Question: SQLite has [Data Change Notification
Callbacks](http://www.sqlite.org/c3ref/update_hook.html) available in the C
API. Can these callbacks be used from the SQLite CLI, or from Bash or from
Python?
If so, how?
Answer: > Can these callbacks be used from the SQLite CLI...
Reading through the SQLite source code, it doesn't look like that function is
used anywhere in the CLI source code, so I doubt you can do it via the CLI.
> ...or from Bash...
Not sure what you mean by that.
> ...or from Python?
It's not exposed via the standard
[`sqlite3`](http://docs.python.org/2/library/sqlite3.html) module, but you can
use it with the [`ctypes`](http://docs.python.org/2/library/ctypes.html)
module.
> If so, how?
Here's a quick n' dirty example of using it via `ctypes`...
from ctypes import *
# Define some symbols
SQLITE_DELETE = 9
SQLITE_INSERT = 18
SQLITE_UPDATE = 23
# Define our callback function
#
# 'user_data' will be the third param passed to sqlite3_update_hook
# 'operation' will be one of: SQLITE_DELETE, SQLITE_INSERT, or SQLITE_UPDATE
# 'db name' will be the name of the affected database
# 'table_name' will be the name of the affected table
# 'row_id' will be the ID of the affected row
def callback(user_data, operation, db_name, table_name, row_id):
if operation == SQLITE_DELETE:
optext = 'Deleted row'
elif operation == SQLITE_INSERT:
optext = 'Inserted row'
elif operation == SQLITE_UPDATE:
optext = 'Updated row'
else:
optext = 'Unknown operation on row'
s = '%s %ld of table "%s" in database "%s"' % (optext, row_id, table_name, db_name)
print s
# Translate into a ctypes callback
c_callback = CFUNCTYPE(c_void_p, c_void_p, c_int, c_char_p, c_char_p, c_int64)(callback)
# Load sqlite3
dll = CDLL('libsqlite3.so')
# Holds a pointer to the database connection
db = c_void_p()
# Open a connection to 'test.db'
dll.sqlite3_open('test.db', byref(db))
# Register callback
dll.sqlite3_update_hook(db, c_callback, None)
# Create a variable to hold error messages
err = c_char_p()
# Now execute some SQL
dll.sqlite3_exec(db, 'create table foo (id int, name varchar(255))', None, None, byref(err))
if err:
print err.value
dll.sqlite3_exec(db, 'insert into foo values (1, "Bob")', None, None, byref(err))
if err:
print err.value
...which prints out...
Inserted row 1 of table "foo" in database "main"
...on the first run and...
table foo already exists
Inserted row 2 of table "foo" in database "main"
...on the second run.
|
Tkinter not displaying image
Question: I have this code:
from tkinter import *
import urllib
import urllib.request
from bs4 import BeautifulSoup
import Pydeck
import sys
from collections import defaultdict
root = Tk()
name=""
def buttonclicked():
name()
picture()
def name():
all_lists=[] #all lists
text = inputfield.get()
Pydeck.loadDatabase('DATABASE PATH')
cardName = Pydeck.getCardsFromName(text)
if not cardName == "":
c = Pydeck.Card(cardName)
tex.insert(END, c.name)
level="\nLevel %s" % c.level + " " + c.attribute + " " + c.typestring
tex.insert(END, level)
atk="\nAtk: %s" % c.attack
tex.insert(END, atk)
defe="\nDef: %s" % c.defense
tex.insert(END, defe)
typestring='\n%s' %c.typestring
desc='\n%s' %c.description
seperator='\n--------------------\n'
tex.insert(END, typestring)
tex.insert(END, desc)
tex.insert(END,seperator)
#--
tex.see(END) # Scroll if necessary
return c.cardID
def picture():
text = inputfield.get()
gifdir = "PICTURE FOLDERS PATH"
Pydeck.loadDatabase('DATABASE PATH')
cardName = Pydeck.getCardsFromName(text)
if not cardName == "":
c=Pydeck.Card(cardName)
filename='{}.gif' .format(c.cardID)
img = PhotoImage(file=gifdir+filename)
can = Canvas(root)
can.pack(fill=BOTH,side='top')
can.config(width=img.width(), height=img.height())
can.create_image(2, 2, image=img, anchor=NW)
tex=Text(root)
tex.pack(side='right')
inputfield = Entry(root)
inputfield.pack(side='bottom')
but = Button(root,text="Enter Name", command = buttonclicked) #Calls name function
but.pack(side='bottom')
text = inputfield.get()
root.mainloop()
Ok, so in short the the program is in Tkinter for Python 3.3. It asks the user
to input a name of a monster, it then searches for the monster in the database
and returns the monster's attributes this is done in the `name` function. I
want it to display a picture of the monster which is where I'm running into
trouble. So the `picture` function takes one of the attributes specifically
the `cardID` attribute and uses that as the name of the gif file. However it
doesn't display the picture and I don't know why. Does anyone know why?
Answer: In order to get a stripped-down version of your code to display a .gif test
image, I had to add a`global img`statement to the`picture()`function so
the`PhotoImage`object that variable name refers to would not be destroyed when
the function returns.
It seems strange that`Canvas.create_image()`doesn't increment the reference
count of the`image`object it's passed...looks like it's a [documented
bug](http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm).
**Update:** For reasons I don't completely understand, adding a`can.img =
img`right after the`can = Canvas(root)`in the`picture()`function accomplishes
the same thing in a better way than creating a global named`img`in my opinion.
Display from working version:

|
Python urllib2 Images Distorted
Question: I'm making a program using the website <http://placekitten.com>, but I've run
into a bit of a problem. Using this:
im = urllib2.urlopen(url).read()
f = open('kitten.jpeg', 'w')
f.write(im)
f.close()
The image turns out distorted with mismatched colors, like this:
<http://imgur.com/zVg64Kn.jpeg>
I was wondering if there was an alternative to extracting images with urllib2.
If anyone could help, that would be great!
Answer: You need to open the file in binary mode:
f = open('kitten.jpeg', 'wb')
Python will otherwise translate line endings to the native platform form, a
transformation that breaks binary data, as documented for the [`open()`
function](http://docs.python.org/2/library/functions.html#open):
> The default is to use text mode, which may convert `'\n'` characters to a
> platform-specific representation on writing and back on reading. Thus, when
> opening a binary file, you should append `'b'` to the mode value to open the
> file in binary mode, which will improve portability.
When copying data from a URL to a file, you could use
[`shutil.copyfileob()`](http://docs.python.org/2/library/shutil.html#shutil.copyfileobj)
to handle streaming efficiently:
from shutil import copyfileobj
im = urllib2.urlopen(url)
with open('kitten.jpeg', 'wb') as out:
copyfileobj(im, out)
This will read data in chunks, avoiding filling memory with large blobs of
binary data. The `with` statement handles closing the file object for you.
|
How do I get python code to loop every x mins between the times y and z?
Question: This might be incredibly easy but how do I get python code to loop every x
mins between the times y and z?
For example if I wanted my script to run between midnight (00:00) through to
10 pm (22:00) looping every 5 minutes.
Answer: Try the _[sched_ module](http://docs.python.org/2.7/library/sched.html#module-
sched) in the standard library. Here's an example of calling a function once
per second, starting five seconds in the future, and ending ten seconds in the
future:
from sched import scheduler
from time import time, sleep
s = scheduler(time, sleep)
def run_periodically(start, end, interval, func):
event_time = start
while event_time < end:
s.enterabs(event_time, 0, func, ())
event_time += interval
s.run()
if __name__ == '__main__':
def say_hello():
print 'hello'
run_periodically(time()+5, time()+10, 1, say_hello)
Alternatively, you can work with
[threading.Timer](http://docs.python.org/2.7/library/threading.html#threading.Timer),
but you need to do a little more work to get it to start at a given time, run
every five minutes, and stop at a fixed time.
|
Python program won't respond until keyboard interrupt
Question: I'm trying to draw an image with PyGame, and I copied this code from Adafruit.
It's strange, seems nothing displays on the screen until I Ctrl-C, at which
time it shows the image. Then the image stays on the screen until I press
Ctrl-C again. I then get the following message:
> Traceback (most recent call last):
> File "RaspiDisplay.py", line 60, in
> time.sleep(10)
> KeyboardInterrupt
What's going on? By the way, I'm running this via ssh on a raspberry pi, with
Display set to 0 (my TV) If I put a print statement in **init** , that also
doesn't print until I press Ctrl-C.
import os
import pygame
import time
import random
class pyscope :
screen = None;
def __init__(self):
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
# Clear the screen to start
self.screen.fill((0, 0, 0))
# Initialise font support
pygame.font.init()
# Render the screen
pygame.display.update()
def __del__(self):
"Destructor to make sure pygame shuts down, etc."
def test(self):
# Fill the screen with red (255, 0, 0)
red = (255, 0, 0)
self.screen.fill(red)
# Update the display
pygame.display.update()
# Create an instance of the PyScope class
scope = pyscope()
scope.test()
time.sleep(10)
Answer: You're not running an event loop anywhere. Instead, you're just initializing
everything, and then going to sleep for 10 seconds. During that 10 seconds,
your code is doing nothing, because that's what you told it to do. That means
no updating the screen, responding to mouse clicks, or anything else.
There are a few different ways to drive pygame, but the simplest is something
like this:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# any other event handling you need
# all the idle-time stuff you want to do each frame
# usually ending with pygame.display.update() or .flip()
See the [tutorial](http://www.pygame.org/docs/tut/intro/intro.html) for more
information.
* * *
As a side note, your initialization code has a bunch of problems. You iterate
through three drivers, but you only set `SDL_VIDEODRIVER` once, so you're just
trying `'fbcon'` three times in a row. Also, you've got code to detect the X
display, but you don't allow pygame/SDL to use X, so… whatever you were trying
to do there, you're not doing it. Finally, you don't need a `found` flag in
Python for loops; just use an `else` clause.
|
using twitter api from python to post messages
Question: [diveintopython3](http://www.diveintopython3.net/http-web-services.html) tells
how you can post a message to [`identi.ca`](http://identi.ca/)
>>> from urllib.parse import urlencode
>>> import httplib2
>>> httplib2.debuglevel = 1
>>> h = httplib2.Http('.cache')
>>> data = {'status': 'Test update from Python 3'}
>>> h.add_credentials('diveintomark', 'MY_SECRET_PASSWORD', 'identi.ca')
>>> resp, content = h.request('https://identi.ca/api/statuses/update.xml',
... 'POST',
... urlencode(data),
... headers={'Content-Type': 'application/x-www-form-urlencoded'})
I thought I'd do the same with twitter..
Then,I found out that they don't use basic authentication,but uses oauth.. so
I thought [this library](https://github.com/mikeknapp/AppEngine-OAuth-Library)
would help
But the docs show that I need some kind of consumer_key etc for
authorisation..
I have a twitter account where I login with `[email protected]` as username
and `mypassword` as password.Is there some way I can use these for
authorization?
Answer: You need to register your app to get that consumer key, and many other
essentials informations.
Here you go : <https://dev.twitter.com/apps>
Some explanations : <https://dev.twitter.com/docs/faq#7447>
As you are about to play with the API please note this link to the API
console, I found it always really useful : <https://dev.twitter.com/console>
|
How can I speed up this really basic python script for offsetting lines of numbers
Question: I have a simple text file which contains numbers in ASCII text separated by
spaces as per this example.
150604849
319865.301865 5810822.964432 -96.425797 -1610
319734.172256 5810916.074753 -52.490280 -122
319730.912949 5810918.098465 -61.864395 -171
319688.240891 5810889.851608 -0.339890 -1790
*<continues like this for millions of lines>*
basically I want to copy the first line as is, then for all following lines I
want to offset the first value (x), offset the second value (y), leave the
third value unchanged and offset and half the last number.
I've cobbled together the following code as a python learning experience
(apologies if it crude and offensive, truly I mean no offence) and it works
ok. However the input file I'm using it on is several GB in size and I'm
wondering if there's ways to speed up the execution. Currently for a 740 MB
file it takes 2 minutes 21 seconds
import glob
#offset values
offsetx = -306000
offsety = -5806000
files = glob.glob('*.pts')
for file in files:
currentFile = open(file, "r")
out = open(file[:-4]+"_RGB_moved.pts", "w")
firstline = str(currentFile.readline())
out.write(str(firstline.split()[0]))
while 1:
lines = currentFile.readlines(100000)
if not lines:
break
for line in lines:
out.write('\n')
words = line.split()
newwords = [str(float(words[0])+offsetx), str(float(words[1])+offsety), str(float(words[2])), str((int(words[3])+2050)/2)]
out.write(" ".join(newwords))
Many thanks
Answer: Don't use `.readlines()`. Use the file directly as an iterator:
for file in files:
with open(file, "r") as currentfile, open(file[:-4]+"_RGB_moved.pts", "w") as out:
firstline = next(currentFile)
out.write(firstline.split(None, 1)[0])
for line in currentfile:
out.write('\n')
words = line.split()
newwords = [str(float(words[0])+offsetx), str(float(words[1])+offsety), words[2], str((int(words[3]) + 2050) / 2)]
out.write(" ".join(newwords))
I also added a few Python best-practices, and you don't need to turn
`words[2]` into a float, then back to a string again.
You could also look into using the `csv` module, it can handle splitting and
rejoining lines in C code:
import csv
for file in files:
with open(file, "rb") as currentfile, open(file[:-4]+"_RGB_moved.pts", "wb") as out:
reader = csv.reader(currentfile, delimiter=' ', quoting=csv.QUOTE_NONE)
writer = csv.writer(out, delimiter=' ', quoting=csv.QUOTE_NONE)
out.writerow(next(reader)[0])
for row in reader:
newrow = [str(float(row[0])+offsetx), str(float(row[1])+offsety), row[2], str((int(row[3]) + 2050) / 2)]
out.writerow(newrow)
|
Emacs and Git show wrong time on Windows
Question: Emacs is two hours off from the system time. I tried to google for the
problem, but no luck. What do I need to configure to correct this? I suspect
this to be the difference from GMT to where I live (I'm in GMT+2 zone, that
is, if I subtract from system time 2, I'll get the time in Emacs). So... maybe
it's some locale settings?
I just messed up a git repository because of that: commits made through
`magit` used Emacs time, and placed them before the commits made by someone
else :(

Here, I've added a screenshot showing the difference. The output from the
`date` is the correct time, but the time on the modeline fringe is wrong.
**EDIT0:**
It appears Stefan is right, and the time in Git is not connected to time in
Emacs (the screenshot below is from Cygwin terminal).
This question is as relevant to Git as it is to Emacs - somehow they are using
some system API that falls out of sync on my PC - and that is something I need
to set up to align them on it. The question is what is that setting they both
use?

**EDIT1:**
Here's the code that Emacs uses to retrieve the time, afaik:
/* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
int
gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
{
struct _timeb tb;
_ftime (&tb);
tv->tv_sec = tb.time;
tv->tv_usec = tb.millitm * 1000L;
/* Implementation note: _ftime sometimes doesn't update the dstflag
according to the new timezone when the system timezone is
changed. We could fix that by using GetSystemTime and
GetTimeZoneInformation, but that doesn't seem necessary, since
Emacs always calls gettimeofday with the 2nd argument NULL (see
current_emacs_time). */
if (tz)
{
tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
tz->tz_dsttime = tb.dstflag; /* type of dst correction */
}
return 0;
}
And it looks like it gets `tz` wrong. I don't know what `_ftime` is - but it
doesn't seem to be defined in Emacs' sources, this must come from elsewhere...
**Some more research:**
SBCL installed from MSI gives this:
(defconstant *day-names*
'("Monday" "Tuesday" "Wednesday"
"Thursday" "Friday" "Saturday" "Sunday"))
(multiple-value-bind
(second minute hour date month year day-of-week dst-p tz)
(get-decoded-time)
(format t "It is now ~2,'0d:~2,'0d:~2,'0d of ~a, ~d/~2,'0d/~d (GMT~@d)"
hour minute second (nth day-of-week *day-names*)
month date year (- tz)))
Output: _(actual time is 12:56)_
It is now 10:56:55 of Tuesday, 6/04/2013 (GMT+0)
Perl from ActivePerl (installed from Cygwin):
$now = localtime;
print $now;
Output: _(actual time is 12:52)_
Tue Jun 4 12:52:17 2013
CPython, installed from MSI.
import datetime
str(datetime.datetime.now())
Output: _(actual time is 13:03)_
2013-06-04 11:03:49.248000
JavaScript, Node.js, installed from MSI:
Date();
Output: _(actual time is 12:09)_
Tue Jun 04 2013 10:09:05 GMT+0000 (IST)
Bash (Cygwin):
$ date
Output: _(actual time is 13:10)_
04 Jun, 2013 13:10:37
C#:
using System;
namespace TestTime
{
class Program
{
static void Main(string[] args)
{
DateTime d = DateTime.Now;
Console.WriteLine("Today: {0}", d);
Console.ReadLine();
}
}
}
Output: _(actual time is 13:13)_
Today: 04-Jun-13 13:13:37
**EDIT2:**
Today our sysadmin gave me a VM to move my stuff to. Interestingly, what
happened there is that this time I got Git through Cygwin, and now Git shows
correct times. Emacs, however, still shows wrong time. Python, (not the one
bundled with Cygwin) shows correct time if launched from Cygwin and wrong time
if launched from Emacs! SBCL shows wrong time no matter how it is launched.
Is it possible this is some network setting? Perhaps something to do with how
Windows synchronizes system time?
Answer: Windows programs get timezone info from the system where you set it via
control panel. Time itself can be set manually too, but it is more usual to
let Windows synchronize with time servers via [Windows Time
Service](http://technet.microsoft.com/cs-
cz/library/cc773263%28v=ws.10%29.aspx) (NTP-based; for usage see [WinXP
support article](http://support.microsoft.com/kb/307897/en-us)). AFAIK Windows
Time Service has nothing to do with timezone and is the only network-related
thing involved in the problem.
Cygwin programs should in theory behave the same way as on any other *NIX.
They get the timezone information from **`/etc/localtime` file** or **`TZ`
environment variable**. In my case (Debian), `/etc/localtime` is a copy of
`/usr/share/zoneinfo/Europe/Prague`, but it could be a symlink pointing to
that location as well. `TZ` can contain path relative to `/usr/share/zoneinfo`
and takes precedence over `/etc/localtime`.
Practice is a different story. According to [a thread on Cygwin mailing
list](http://cygwin.com/ml/cygwin/2012-03/msg00048.html), Microsoft C runtime
(mscrt*.dll) has extremely outdated timezone handling and it is used for non-
Cygwin programs. This is consistent with the results you are getting. Related
technical info is in [a thread from August
2005](http://cygwin.com/ml/cygwin/2005-08/msg00126.html) and [a related one
from May 2010](http://cygwin.com/ml/cygwin/2010-05/msg00455.html).
There is a [work-around for
Python](http://stackoverflow.com/questions/11958870/logging-module-for-python-
reports-incorrect-timezone-under-cygwin) already posted on SO and [exactly the
same for C++](http://stackoverflow.com/questions/11655003/localtime-returns-
gmt-for-windows-programs-running-on-cygwin-shells), which has a more brief
explanation of the MSCRT problem than the previously linked threads.
Maybe Emacs has something special to do with the issue. [A February 2009
message on GNU Emacs developers mailing
list](http://lists.gnu.org/archive/html/emacs-devel/2009-02/msg00305.html)
reports Emacs 22.3 displays correct time while Emacs 23 not. Following advice
from a reply, the author posts [the report to Cygwin mailing
list](http://cygwin.com/ml/cygwin/2009-02/msg00148.html) – but gets no reply.
[December 2012](http://cygwin.com/ml/cygwin/2009-12/msg00972.html) the issue
is solved by docummenting it and its workaround (see
`/usr/share/doc/Cygwin/emacs.README`). _I don't have Cygwin and cannot find
this file in its CVS, so please edit my answer with the info from there._
Personally I think that setting (and exporting) TZ environment variable in
your `~/.profile` would be a good idea. Cygwin obviously has broken timezone
handling, so overriding everything related should be the safest thing to do as
it leaves just a little room for black magic. Maybe
[`tzset`](http://www.cygwin.com/cygwin-ug-net/using-utils.html#tzset) will
work, maybe it won't and you'll have to set your timezone to a constant value.
Try [googling for „timezone“ at
Cygwin.com](https://www.google.com/search?q=timezone+site%3acygwin.com) for
more resources.
|
Python remove duplicate cases that are in inverted matrix
Question: I have a list that looks like this:
relationShipArray = []
relationShipArray.append([340859419124453377, 340853571828469762])
relationShipArray.append([340859419124453377, 340854579195432961])
relationShipArray.append([340770796777660416, 340824159120654336])
relationShipArray.append([340509588065513473, 340764841658703872])
relationShipArray.append([340478540048916480, 340671891540934656])
relationShipArray.append([340853571828469762, 340854579195432961])
relationShipArray.append([340842710057492480, 340825411573399553])
relationShipArray.append([340825411573399553, 340770796777660416])
relationShipArray.append([340825411573399553, 340824159120654336])
relationShipArray.append([340824159120654336, 340770796777660416])
relationShipArray.append([340804620295221249, 340825411573399553])
relationShipArray.append([340684236191313923, 340663388122279937])
relationShipArray.append([340663388122279937, 340684236191313923])
relationShipArray.append([340859507280318464, 340859419124453377])
relationShipArray.append([340859507280318464, 340853571828469762])
relationShipArray.append([340859507280318464, 340854579195432961])
relationShipArray.append([340854599697178624, 340845885439229952])
relationShipArray.append([340836561937641472, 340851694759972864])
relationShipArray.append([340854579195432961, 340853571828469762])
relationShipArray.append([340844519832580096, 340854599697178624])
relationShipArray.append([340814054610305024, 340748443670683648])
relationShipArray.append([340851694759972864, 340836561937641472])
relationShipArray.append([340748443670683648, 340814054610305024])
relationShipArray.append([340739498356912128, 340825992832638977])
As you can see there are cases that are duplicated. e.g.
[340853571828469762, 340854579195432961]
is the same as (but inverted)
[340854579195432961, 340853571828469762]
What is the best way (with some efficiency but can live without it if need be)
to remove the duplicates from this list? So in this case I would **keep**
`[340853571828469762, 340854579195432961]`, but **remove** the
`[340854579195432961, 340853571828469762]`.
Answer: Use an OrderedDict if you need to keep the order:
from collections import OrderedDict
>>> L = [[1, 2], [4, 5], [1,2], [2, 1]]
>>> [[x, y] for x, y in OrderedDict.fromkeys(frozenset(x) for x in L)]
[[1, 2], [4, 5]]
**EDIT 1**
If the order is not important you can get away with a set:
>>> [[x, y] for x, y in set(frozenset(x) for x in L)]
[[1, 2], [4, 5]]
**EDIT 2**
A more generic solution that works for lists of varying lenght, not only with
two elements:
[list(entry) for entry in set(frozenset(x) for x in L)]
[list(entry) for entry in OrderedDict.fromkeys(frozenset(x) for x in L)]
|
How to find every integer that is the closest to the antilogarithm (10base) for a series of n*0.1 (in Python)
Question: In my algorithm I want to evaluate if the current integer n happens to be
closest to the antilogarithm of any positive multiple of 0.1, so 0.1, 1.0,
1.1, 7.9, 21.5 etc.
Antilog? AntiLog(x) = 10x
I found an online calculator that finds the antilog here:
<http://ncalculators.com/number-conversion/anti-log-logarithm-calculator.htm>
but nowhere I could find any examples of doing this in Python, or any other
programming language.
If I can't use Python to find the antilog of a series of numbers I would have
to resort to storing a list of antilog values in my program, for performance
I'm might consider that anyways but nevertheless it would be great to figure
out how to do this in code.
**Update:** With the code from first answer I was able to do it, this code
fully demonstrates all I was trying to do:
#!/usr/bin/python
import sys
import math
for x in xrange(1, 1000000):
target = round(math.log10(x),1)
int_antilog = int(10**target+0.5) #fast round() alternative
if (x == int_antilog):
print 'do something at call ' + str(x)
Answer: Python has a [power
operator](http://docs.python.org/2/reference/expressions.html#the-power-
operator) that performs the exponentiation you want to do:
def antilog(x):
return 10 ** x
Examples:
>>> antilog(0.1)
1.2589254117941673
>>> antilog(3)
1000
>>> inputs = [0.1, 1.0, 1.1, 7.9, 21.5]
>>> outputs = [antilog(x) for x in inputs]
>>> print outputs
[1.2589254117941673, 10.0, 12.589254117941675, 79432823.47242822, 3.1622776601683794e+21]
Round and convert to integers in your favourite way, and you'll be good to go.
|
TypeError when multiplying matrices
Question: I'm trying to multiply some matrices together and I keep getting a type error
for the last multiplication (calculating C). All the other multiplications
proceed correctly, but I get the error:
Traceback (most recent call last):
File "C:\Python27\Lab2_MatMult_template.py", line 31, in <module>
C = matlib.matmul(A1,B)
File "C:\Python27\lib\site-packages\matlib.py", line 158, in matprod
t = sum([A[i][k] * B[j] for k in range(p)])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
I think I may have defined the B matrix incorrectly (it is a column vector)
but I can't seem to figure out the exact cause
# Template for multiplying two matrices
import matlib
import math
# Use help(math) to see what functions
# the math library contains
RShoulderPitch = 0
RElbowRoll = 0
# Matrix A
A1 = [[1, 0, 0, 0], [0,1,0,0], [0,0,1,0], [0,0,0,1]]
A2 = [[-1, 0, 0, 0], [0,0,-1,0], [0,-1,0,100], [0,0,0,1]]
A3 = [[0, -1, 0, 0], [1,0,0,0], [0,0,1,98], [0,0,0,1]]
A4 = [[math.cos(-RShoulderPitch), 0, -math.sin(-RShoulderPitch), 105*math.cos(-RShoulderPitch)], [math.sin(-RShoulderPitch),0,math.cos(-RShoulderPitch),105*math.sin(-RShoulderPitch)], [0,-1,0,15], [0,0,0,1]]
# Matrix B
B = [[0],[0],[0],[2]]
T = matlib.matmul(A3,A4)
T = matlib.matmul(A2,T)
T = matlib.matmul(A1,T)
C = matlib.matmul(B,T)
print('C=')
matlib.matprint(T, format='%8.1f')
def matmul(A, B):
"""
Computes the product of two matrices.
2009.01.16 Revised for matrix or vector B.
"""
m, n = matdim(A)
p, q = matdim(B)
if n!= p:
return None
try:
if iter(B[0]):
q = len(B[0])
except:
q = 1
C = matzero(m, q)
for i in range(m):
for j in range(q):
if q == 1:
t = sum([A[i][k] * B[j] for k in range(p)])
else:
t = sum([A[i][k] * B[k][j] for k in range(p)])
C[i][j] = t
return C
Answer: You only have lists but need matrices. Write:
A1 = matlib.matrix([[1, 0, 0, 0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])
A2 = matlib.matrix(...
for all your matrices.
|
Send images using sockets Python
Question: I have some problems with this code... send not the integer image but some
bytes, is there someone than can help me? I want to send all images I find in
a folder. Thank you.
# CLIENT
import socket
import sys
import os
s = socket.socket()
s.connect(("localhost",9999)) #IP address, port
sb = 'c:\\python27\\invia'
os.chdir(sb) #path
dirs =os.listdir(sb) #list of file
print dirs
for file in dirs:
f=open(file, "rb") #read image
l = f.read()
s.send(file) #send the name of the file
st = os.stat(sb+'\\'+file).st_size
print str(st)
s.send(str(st)) #send the size of the file
s.send(l) #send data of the file
f.close()
s.close()
# SERVER
import socket
import sys
import os
s = socket.socket()
s.bind(("localhost",9999))
s.listen(4) #number of people than can connect it
sc, address = s.accept()
print address
sb = 'c:\\python27\\ricevi'
os.chdir(sb)
while True:
fln=sc.recv(5) #read the name of the file
print fln
f = open(fln,'wb') #create the new file
size = sc.recv(7) #receive the size of the file
#size=size[:7]
print size
strng = sc.recv(int(size)) #receive the data of the file
#if strng:
f.write(strng) #write the file
f.close()
sc.close()
s.close()
Answer: The parameter to
[`socket.recv`](http://docs.python.org/2/library/socket#socket.socket.recv)
only specifies the maximum buffer size for receiving data packages, it doesn't
mean exactly that many bytes will be read.
So if you write:
strng = sc.recv(int(size))
you won't necessarily get all the content, specially if `size` is rather
large.
You need to read from the socket in a loop until you have actually read `size`
bytes to make it work.
|
Making a video with opencv, getting only 1 frame
Question: I've been trying to add a video making module to my program using opencv, but
try as I might I can't get the video to show more than 1 frame. I got this
example code while searching for answers ([Creating a video using OpenCV 2.4.0
in python](http://stackoverflow.com/questions/14440400/creating-a-video-using-
opencv-2-4-0-in-python))
import cv2
from cv import *
img1 = cv2.imread('i001.png')
img2 = cv2.imread('i002.png')
img3 = cv2.imread('i003.png')
height , width , layers = img1.shape
video=cv2.VideoWriter('test.avi', CV_FOURCC('D', 'I', 'V', 'X'),1,(width,height))
video.write(img1)
video.write(img2)
video.write(img3)
cv2.destroyAllWindows()
video.release()
This creates a video that runs for 3 seconds, but shows only the first image
for all 3 seconds. Is there a codec error or am I missing something?
Answer: u can use :
cv.WriteFrame(writer, image)
like this :
import cv
img1 = cv.LoadImage('i001.png')
img2 = cv.LoadImage('i002.png')
img3 = cv.LoadImage('i003.png')
writer=cv.CreateVideoWriter(filename, fourcc, fps, frame_size, is_color)
cv.WriteFrame(writer, img1)
cv.WriteFrame(writer, img2)
cv.WriteFrame(writer, img3)
look also :
<http://opencv.willowgarage.com/documentation/python/highgui_reading_and_writing_images_and_video.html?highlight=createvideowriter#CreateVideoWriter>
|
QMutex.unlock doesn't wake all blocked threads
Question: I use Qt 4.8.4 and PyQt 4.10
Here is my test code:
#!/usr/bin/env python3
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Thread1(QThread):
def run(self):
print('thread1 %d' % QThread.currentThreadId())
mutex.lock()
QThread.sleep(5)
mutex.unlock()
class Thread2(QThread):
def run(self):
tid = QThread.currentThreadId()
print('%d tid enters' % tid)
mutex.lock()
print(tid)
app = QApplication(sys.argv)
print('main thread %d' % QThread.currentThreadId())
mutex = QMutex()
t = Thread1()
t.start()
QThread.sleep(1)
threads = [Thread2() for i in range(10)]
for thread in threads:
thread.start()
app.exec()
My problem is: when thread1 calls mutex.unlock(), only one blocked thread is
waken.
Here is the output:
main thread 140017224202048
thread1 140016996386560
140016987993856 tid enters
140016979601152 tid enters
140016962815744 tid enters
140016971208448 tid enters
140016672044800 tid enters
140016646866688 tid enters
140016638473984 tid enters
140016954423040 tid enters
140016663652096 tid enters
140016655259392 tid enters
140016987993856
The document doesn't say anything about how to wake all blocked. How can I do
that? THX
Answer: A [mutex](http://qt-project.org/doc/qt-4.8/qmutex.html#details) by definition
limits (or protects) one piece of code so that only _one_ thread can access it
at a time. So you can't "wake" all threads if they all wait for one mutex,
maybe you need many mutexes (one for each "resource") or depending or the
design and constrains or your real project (since you posted the code from a
"test application") maybe a [semaphore](http://qt-
project.org/doc/qt-4.8/qsemaphore.html#details) will be better suited.
|
Dropbox python sdk import error
Question: I am trying to use the dropbox sdk for python. I installed a virtual
enviroment and used pip install to install dropbox-sdk. When I try to run the
example code (see below) I get a importerror client cannot be found, but if I
try to do it from the interactive intreperter it works. So what am I doing
wrong. APP key and secret key and acces_type ommitted.
Answer: Update: I found the problem, i called my own file dropbox.py and in that file
imported dropbox. I accidently imported my own file. Renamed my file and now
it works.
|
Django register and login - explained by example
Question: Can someone please explain in details how to make a **registration** and
**authentication** in as easy words as possible ? I made authentication
(login) with `django.contrib.auth` but what I want to get is a full
register(social/non)+login. Already saw the `django-allauth`, `django-social-
auth`, `django-social` but still can't get it working without hacking a lot.
Heard that `django-registration` and `django-profiles` can make it a lot
easier, but i can't handle it. For example,
~/.virtualenvs/plinter/lib/python2.7/site-packages/registration/backends/default/urls.py
needs a small hack to work:
# from django.views.generic.simple import direct_to_template
from django.views.generic import RedirectView
...
RedirectView.as_view(url='/registration/activation_complete.html'),
# direct_to_template,
# {'template': 'registration/activation_complete.html'},
...
The DjangoBook gives _simple_ examples of [Contact and search
forms](http://www.djangobook.com/en/2.0/chapter07.html). But i can't expand it
on user registration and login. So can anyone give kis example of **working**
**registration** and **login**? **
# Update
** [Here](http://stackoverflow.com/questions/10180764/django-auth-login-
problems) is a simple example of login. Now `django-allauth` or social auth or
`registration2` are in consideration... **
# Update2
** `django-allauth` seems to be the best solution for easier authentication.
Add correctly apps in settings, register fb/google/etc apps and register
through admin and use template inheritance to change default pages design.
Answer: [THIS](http://code.techandstartup.com/django/registration/) is a **very good**
tutorial about login & Co. It explains very well how to perform login by
ourself ad override existing django login pages.
# UPDATE:
**Here Overview for Registration and Login. For more details go to the link.**
**To Register:**
> **Views and URLs**
>
> Go to the lower site folder (where the settings.py file is) and open the
> views.py file. At the top make sure the following imports are included. Add
> them if not:
>
>
> from django.shortcuts import
> render_to_response from django.http import HttpResponseRedirect from
> django.contrib.auth.forms import UserCreationForm from
> django.core.context_processors import csrf
>
>
> Below that add the following functions (you can put them after the Login
> functions):
>
>
> def
> register(request):
> if request.method == 'POST':
> form = UserCreationForm(request.POST)
> if form.is_valid():
> form.save()
> return HttpResponseRedirect('/accounts/register/complete')
>
> else:
> form = UserCreationForm()
> token = {}
> token.update(csrf(request))
> token['form'] = form
>
> return render_to_response('registration/registration_form.html',
> token)
>
> def registration_complete(request):
> return
> render_to_response('registration/registration_complete.html')
>
>
> Open the urls.py file in the site folder (same folder as settings.py). Below
> urlpatterns = patterns('', insert the following lines.
>
>
> # Registration URLs
> url(r'^accounts/register/$', 'simplesite.views.register',
> name='register'),
> url(r'^accounts/register/complete/$',
> 'simplesite.views.registration_complete',
> name='registration_complete'),
>
>
> **Templates** We will assume your site already has a templates directory and
> a base.html file with the navigation bar. Open the base.html file and in the
> nav element add a navigation menu link to the login page
>
>
> <a href="/accounts/register">register</a>
>
>
> If one does not already exist, go to the templates folder and create a
> folder inside it named registration. Create a file called
> registration_form.html, save it to the templates/registration folder, then
> populate it with the following:
>
>
> {% extends "base.html" %} {% block title %}Register{%
> endblock %} {% block content %}
>
> <h2>Registration</h2>
>
> <form action="/accounts/register/" method="post">{% csrf_token %}
> {{form.as_p}} <input type="submit" value="Register" />
>
> </form>
>
> {% endblock %}
>
>
> Create a file called registration_complete.html, save it to the
> templates/registration folder, and populate it with the following:
>
>
> {% extends "base.html" %} {% block title %}You are
> Registered{% endblock %} {% block content %}
>
> <h2>Thank you for Registering</h2> <p><a
> href="/accounts/login/">Please Login</a></p>
>
> {% endblock %}
>
**To Login:**
> **Views and URLs** Open the views.py file in the lower site folder (where
> the settings.py file is). If there isn't one then create and save it. At the
> top of the file insert the following import: from django.shortcuts import
> render_to_response Below that you only need to add one function rendering
> the loggedin page. The other functions (login and logout) are in the
> views.py file in the Django Auth folder.
>
>
> def loggedin(request):
> return render_to_response('registration/loggedin.html')
>
>
> # Optionally, if you want to show their username when they login then call
> their username in the view. Change the loggedin function to:
>
>
> def loggedin(request):
> return render_to_response('registration/loggedin.html',
> {'username': request.user.username})
>
>
> Open the urls.py file in the site folder (same folder as settings.py). Below
> urlpatterns = patterns('', insert the following lines.
>
>
> # Auth-related URLs:
> url(r'^accounts/login/$', 'django.contrib.auth.views.login',
> name='login'),
> url(r'^accounts/logout/$', 'django.contrib.auth.views.logout',
> name='logout'),
> url(r'^accounts/loggedin/$', 'simplesite.views.loggedin',
> name='loggedin'),
>
>
> With simplesite being the name of the folder that holds the views.py file
> that you are calling. Open the settings.py file and at the bottom insert
> `LOGIN_REDIRECT_URL = '/accounts/loggedin/'`. Django's default is to
> redirect to /accounts/profile when you log in, which is fine if you have an
> profile page at that url. If not you need to change your settings default
> for the Login redirect url to the one holding your loggedin.html page.
>
> **Templates**
>
> We will assume your site already has a templates directory and a base.html
> file with the navigation bar. Open the base.html file and in the nav element
> add a navigation menu link to the login page `<a
> href="/accounts/login">login</a>` Add a logout link too `<a
> href="/accounts/logout">logout</a>` Create a directory called registration
> inside the templates folder. If you do this through the command line, type
> mkdir registration Create a file called login.html, save it to the
> templates/registration folder, and populate it with the following:
>
>
> {% extends "base.html" %}
> {% block title %}Log In{% endblock %}
> {% block content %}
>
> <form method="post" action="{% url 'django.contrib.auth.views.login'
> %}">
> {% csrf_token %}
> <table>
> {{ form.as_table }}
> </table>
>
> <input type="submit" value="login" />
> </form>
>
> {% endblock %}
>
>
> `{{ form.as_table }}` uses the Django Forms module to create the form. You
> can create an unformatted form by using `{{ form }}` without the HTML table
> tags, or have each field put inside paragraph tags with `{{ form.as_p }}`,
> or as an unordered list `{{ form.as_ul }}`. Optionally, you can also lay out
> your own form structure and use the form field tags as follows:
>
>
> {% extends "base.html" %}
> {% block title %}Log In{% endblock %}
> {% block content %}
>
> <form method="post" action="{% url 'django.contrib.auth.views.login'
> %}">
> {% csrf_token %}
>
> {% if form.errors %}
> <p>Your Username or Password were not entered correctly. Please try
> again.</p>
> {% endif %}
>
> <table>
> <tr>
> <td>{{ form.username.label_tag }}</td>
> <td>{{ form.username }}</td>
> <td>{{ form.username.errors }}</td>
> </tr>
> <tr>
> <td>{{ form.password.label_tag }}</td>
> <td>{{ form.password }}</td>
> <td>{{ form.password.errors }}</td>
> </tr>
> </table>
>
> <input type="submit" value="login" />
> </form>
>
> {% endblock %}
>
>
> Create a file called loggedin.html, save it to the templates/registration
> folder, and populate it with the following:
>
>
> {% extends "base.html" %}
> {% block title %}Logged In{% endblock %}
> {% block content %}
>
> <h2>You are logged in</h2>
>
> {% endblock %}
>
>
> If you want to display the username, you would make the adjustment to the
> view discussed in the views section. Then change the loggedin.html template
> to the below (change the wording as you see fit):
>
>
> {% extends "base.html" %}
> {% block title %}Logged In{% endblock %}
> {% block content %}
>
> <h1>Welcome {{username}}</h1>
> <p>Thank you for logging in.</p>
> <p><a href="/accounts/logout/">Logout</a></p>
>
> {% endblock %}
>
>
> Create a file called logged_out.html, save it to the templates/registration
> folder and populate it with the following:
>
>
> {% extends "base.html" %}
> {% block title %}Logged Out{% endblock %}
> {% block content %}
>
> <h2>Logged out!</h2>
> <p><a href="/accounts/login/">Log back in</a></p>
>
> {% endblock %}
>
|
Is there some way to decrease memory requirement in these implementations of Sieve of Eratosthenes
Question: I am using Python 2.7
Among the two implementations of Sieve of Eratosthenes erat() and erat2() that
I wrote erat2() has the benefit that on the 2nd run of erat2() it gives the
results in comparatively much lesser time.
def erat2(num, isprime = [2]):
if num > len(isprime) + 2:
last_original = len(isprime) + 2
isprime += [num for num in xrange(last_original ,num + 1)]
for i in xrange(2,num + 1):
if isprime[i-2]:
if i <= last_original:
j = last_original//i + 1
else:
j = 2
temp = j * i
while temp <= num:
isprime[temp-2] = 0
j += 1
temp = j * i
return filter(lambda x: x != 0, isprime[:num - 1])
def erat(num):
isprime = [num for num in xrange(2,num + 1)]
for i in xrange(2,num + 1):
if isprime[i-2]:
j = 2
temp = j * i
while temp <= num:
isprime[temp-2] = 0
j += 1
temp = j * i
return filter(lambda x: x != 0, isprime)
import time
def t():
num = 100000000
i = 10
while i < num:
s = time.time()
erat2(i)
x = time.time() - s
print "%10d %10f" %(i,x),
s = time.time()
erat(i)
y = time.time() - s
print " %10f" %(y)
i *= 10
To support the fact that on the second run of the code the results will be
much faster some timing analysis is given here. The first column is test
input. The second column is for timing of erat2() and third is for timing of
erat(). As is clear the time is reduced by factor of 7 in second run.
>>> t()
10 0.000000 0.000000
100 0.000000 0.000000
1000 0.000000 0.000000
10000 0.010000 0.010000
100000 0.100000 0.110000
1000000 1.231000 1.410000
10000000 13.605000 15.081000
>>> t()
10 0.000000 0.000000
100 0.000000 0.000000
1000 0.000000 0.000000
10000 0.000000 0.020000
100000 0.020000 0.140000
1000000 0.170000 1.550000
10000000 1.770000 15.752000
The problem that I am facing is that the memory usage spikes after this test
input.
* Is there some optimization that can be done to reduce memory consumption?
* Is such an increase in memory a good implementation practice?
EDIT:
I found a little optimization for both functions erat() and erat2() to
increase the speed. Changed the lambda function from
lambda x: x != 0
to
lambda x: x
The same result but slightly faster. One second faster for num = 10000000.
EDIT2:
Used vartec and btilly's suggestions. Improved erat() to erat3(). Here are the
improved implementation alongwith timing check. Also found that placing
expressions in xrange function led to performance loss. Added variable to
improve performance.
def erat3(num):
''' Improves Sieve of eratosthenes '''
#REQUIRES MATH MODULE
if num < 2:
return []
isprime = [num for num in xrange(3,num + 1,2)]
#temp2's expression placed in xrange function => performance-loss
temp2 = int(math.sqrt(num)) + 1
for i in xrange(3, temp2 ,2):
if isprime[(i-3)/2]:
j = 3
temp = j * i
while temp <= num:
isprime[(temp-3)/2] = 0
j += 2
temp = j * i
return [2] + filter(lambda x: x, isprime)
Timing for erat() and erat3()
>>> t()
10 0.000000 0.000000
100 0.000000 0.000000
1000 0.000000 0.000000
10000 0.010000 0.010000
100000 0.110000 0.040000
1000000 1.241000 0.530000
10000000 14.131000 6.111000
Answer: It is common to have a tradeoff between memory and performance. Which matters
more to you depends on your application.
In this case I would suggest mitigating that by using BitVector (see
<https://pypi.python.org/pypi/BitVector> for details) so that the data
structure you create is much more compact.
Also in this case special casing 2 and only storing odd bits will double
performance, and halve memory, at the cost of slightly more code complexity.
That is probably worth it.
|
python socket and socketserver
Question: I've been trying to make a multi-client server and i finally have and it works
perfectly but what I want to do now is to instead of getting the clients
address, get the client to type their name in and then the program will say
"Bob: Hi guys" instead of "127.0.0.1: Hi guys".
I used a pre-made server and client from python docs. Here's the server:
import socketserver
class MyUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
name = self.request[0].strip()
socket = self.request[1]
print(name,"wrote:".format(self.client_address[0]))
print(data)
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = socketserver.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()
And here's the client:
import socket
import sys
HOST, PORT = "localhost", 9999
data = "".join(sys.argv[1:])
name = "".join(sys.argv[1:])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(bytes(name + "Bob", 'utf-8'), (HOST, PORT))
sock.sendto(bytes(data + "hello my name is Bob", "utf-8"), (HOST, PORT))
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
Everything works fine but for some reason I get this in the server once the
client has connected.
b'Bob' wrote:
b'Bob'
b'hello my name is bob' wrote:
b'hello my name is bob'
I want it to be like:
Bob wrote:
b'Hello my name is bob'
I hope someone can help me, thanks.
Answer: You've got multiple problems here.
* * *
The first is that you're printing `bytes` objects directly:
print(name,"wrote:".format(self.client_address[0]))
That's why you get `b'Bob' wrote:` instead of `Bob wrote:`. When you print a
`bytes` object in Python 3, this is what happens. If you want to decode it to
a string, you have to do that explicitly.
You have code that does that all over the place. It's usually cleaner to use
the `decode` and `encode` methods than the `str` and `bytes` constructors, and
if you're already using `format` there are even nicer ways to deal with this,
but sticking with your existing style:
print(str(name, "utf-8"), "wrote:".format(self.client_address[0]))
* * *
Next, I'm not sure why you're calling `format` on a string with no format
parameters, or why you're mixing multi-argument `print` functions and `format`
calls together. It looks like you're trying to get `self.client_address[0]`,
but you're not doing that. Then again, your desired output doesn't show it,
so… just remove that `format` call if you don't want it, add a `{}` somewhere
in the format string if you do. (You're also probably going to want to decode
`client_address[0]`, too.)
* * *
Next, you store the same value in `name` and `data`:
data = self.request[0].strip()
name = self.request[0].strip()
So, when you later do this:
print(data)
… that's just printing `name` again—and, again, without decoding it. So, even
if you fix the decoding problem, you'll still get this:
Bob wrote:
Bob
… instead of just:
Bob wrote:
To fix that, just get rid of the `data` variable and the `print(data)` call.
* * *
Next, you're sending two separate packets, one with the `name` and the other
with the `data`, but trying to recover both out of each packet. So, even if
you fix all of the above, you're going to get `Bob` in one packet as the name,
and `hello my name is bob` in the next packet, resulting in:
Bob wrote:
hello my name is bob wrote:
If you want this to be stateful, you need to actually store the state
somewhere. In your case, the state is incredibly simple—just a flag saying
whether this is the first message from a given client—but it still has to go
somewhere. One solution is to associate a new state with each address using a
dictionary—although in this case, since the state is either "seen before" or
nothing at all, we can just use a set.
Putting it all together:
class MyUDPHandler(socketserver.BaseRequestHandler):
def __init__(self, *args, **kw):
self.seen = set()
super().__init__(*args, **kw)
def handle(self):
data = self.request[0].strip()
addr = self.client_address[0]
if not addr in self.seen:
print(str(data, "utf-8"), "wrote:")
self.seen.add(addr)
else:
print(str(data, "utf-8"))
socket.sendto(data.upper(), self.client_address)
* * *
Meanwhile, it seems like what you _actually_ want is to store the name from
the first request as your per-client state, so you can reuse it in every
future request. That's almost as easy. For example:
class MyUDPHandler(socketserver.BaseRequestHandler):
def __init__(self, *args, **kw):
self.clients = {}
super().__init__(*args, **kw)
def handle(self):
data = str(self.request[0].strip(), 'utf-8')
addr = self.client_address[0]
if not addr in self.clients:
print(data, "joined!")
self.clients[addr] = data
else:
print(self.clients[addr], 'wrote:', data)
socket.sendto(data.upper(), self.client_address)
|
py2exe and disappeared icon
Question: I am using pyqt, icon is added.
icon.addPixmap(QtGui.QPixmap(_fromUtf8("favicon.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
In setup.py for py2exe, I am trying to add my icon to resources.
from distutils.core import setup
import py2exe
setup(
console=[{
"script" : "manage.py",
"icon_resources": [(1, "favicon.ico")]
}],
options={
"py2exe" : {"includes" : ["sip",]}
}
)
When I start my program from IDE as python script, I see my icon. When I
create exe program with py2exe, my program works well, but icon dissappears.
Answer: The problem is that py2exe doesn't include the qt icon reader plugin.
Data_files parameter added.
from distutils.core import setup
import py2exe
setup(
options={
"py2exe" : {"includes" : ["sip",]}
},
data_files = [
('imageformats', [
r'C:\programs\Python271\Lib\site-packages\PyQt4\plugins\imageformats\qico4.dll'
])],
console=[{
"script" : "manage.py"
}]
)
|
Implementing MVC in Python? (using Flask and MongoKit)
Question: I'm coming from a spaghetti code PHP background. I'm trying to learn MVC by
cutting my teeth on Python with Flask and MongoDB. I think this question could
apply to other situations. It's more of a newbie Python question. But this is
where I'm running into it for the first time with this setup.
I'm using Flask with Blueprints to layout my app. I'm breaking down each major
site feature into a sub directory of myapp (module/blueprint). Here is my
directory structure
**Dir structure**
/proj/config.py
/proj/runserver.py
/proj/myapp/
/proj/myapp/__init__.py
/proj/myapp/static/
/proj/myapp/templates/
/proj/myapp/templates/users/
/proj/myapp/templates/forums/
/proj/myapp/templates/frontend/
/proj/myapp/users/
/proj/myapp/users/__init__.py
/proj/myapp/users/models.py
/proj/myapp/users/views.py
/proj/myapp/forums/ ..
/proj/myapp/frontend/ ..
So I'm trying to implement this simple MongoKit example. But instead of having
it in one file. I need to spread it out across the MVC pattern.
**MongoKit sample**
from flask import Flask, request, render_template, redirect, url_for
from flask.ext.mongokit import MongoKit, Document
app = Flask(__name__)
class User(Document):
__collection__ = 'user'
structure = {
'name': unicode,
'email': unicode,
}
required_fields = ['name', 'email']
use_dot_notation = True
db = MongoKit(app)
db.register([User])
The main part of my app is in **init**.py and it looks like:
**/myapp/__init_ _.py**
from flask import Flask, render_template, abort
from flask.ext.mongokit import MongoKit, Document
from .home.views import mod as home_blueprint
from .users.views import mod as user_blueprint
from .forums.views import mod as forum_blueprint
def create_app():
app = Flask(__name__)
app.config.from_object('config')
# Register blueprints
app.register_blueprint(home_blueprint)
app.register_blueprint(user_blueprint, url_prefix="/users")
app.register_blueprint(forum_blueprint, url_prefix="/forums")
db = MongoKit(app)
@app.errorhandler(404)
def not_found(error):
return render_template('404.html')
@app.errorhandler(500)
def internal_error(exception):
return "Some internal error has taken place. Alert somebody!"
return app
And then I'm not quite sure what to do with the rest. I setup a class in
/myapp/users/models.py like below. I know the last statement isn't defined.
I'm not sure if it goes there or if I need to put it someplace else. Or if it
does go there, how do I get "db" from the create_app() in **init**.py. I
figure this has less to do with MongoKit and basic Python stuff.
**/myapp/users/models.py**
from flask.ext.mongokit import MongoKit, Document
class User(Document):
structure = {
'name': unicode,
'email': unicode,
}
use_dot_notation = True
db.register([User])
Answer: If you want to use create_app function, then I would change your `__init__.py`
to something like:
**`/myapp/__init__.py`**
from flask import Flask, render_template, abort
from flask.ext.mongokit import MongoKit, Document
from .home.views import mod as home_blueprint
from .users.views import mod as user_blueprint
from .forums.views import mod as forum_blueprint
def create_app():
app = Flask(__name__)
app.config.from_object('config')
# Register blueprints
app.register_blueprint(home_blueprint)
app.register_blueprint(user_blueprint, url_prefix="/users")
app.register_blueprint(forum_blueprint, url_prefix="/forums")
db = MongoKit(app)
@app.errorhandler(404)
def not_found(error):
return render_template('404.html')
@app.errorhandler(500)
def internal_error(exception):
return "Some internal error has taken place. Alert somebody!"
return app,db
# Make sure you are calling create_app func below:
(app,db) = create_app()
Now in your models code, you can refer to db variable.
**/myapp/users/models.py**
from flask.ext.mongokit import MongoKit, Document
# import db below like this
from myapp import db
class User(Document):
structure = {
'name': unicode,
'email': unicode,
}
use_dot_notation = True
# ok to do this below
db.register([User])
|
Find string matches count in list using Python
Question: I read a text file for some analysis, each word is appended to a list and
given an id
#!/usr/bin/python3
with fi as myfile:
for line in myfile:
for item in line.split(' '):
db[0].append(id_+1)
db[2].append(item)
...more stuff
Then I search for each word through the list to find its matches, and store
the count as **sim1**. If a match is found, I test if the next word matches
the consecutive one as well, and store its count as **sim2**. Similarly for
**sim3**. My code looks like:
for i in range(id_-3):
sim1=0
sim2=0
sim3=0
for j in range(id_-3):
if i==j: continue;
if db[2][i] == db[2][j]:
sim1 += 1
if db[2][i+1] == db[2][j+1]:
sim2 += 1
if db[2][i+2] == db[2][j+2]:
sim3 += 1
db[3].append(sim1)
db[4].append(sim2)
db[5].append(sim3)
This works, but it's too slow! I believe python provides faster search
methods, but I'm still a Py newbie!
Answer: The slowness in your algorithm mainly comes from the fact that you have an
inner loop which iterates len(db[2]) times contained within an outer loop
which also iterates len(db[2]) times. This means the inner code is executing
len(db[2])^2 times. If your file is large and you are parsing 5000 words, for
example, then the code runs 5000^2 = 25,000,000 times!
So, the angle of attack to solve the problem is to find a way to eliminate or
significantly reduce the cost of that inner loop. Below is an example solution
which only needs to iterate through len(db[2]) one time, and then does a
second separate loop which iterates through a much smaller set of items. There
are a few inner loops within the second iteration, but they run an even
smaller number of times and have almost inconsequential cost.
I timed your algorithm and my algorithm using a text file which weighed in at
about 48kb. Your algorithm averaged about 14 seconds on my computer and my
algorithm averaged 0.6 seconds. So, by taking away that inner loop, the
algorithm is now over 23 times faster. I also made some other minor
optimizations, such as changing the comparison to be between numbers rather
than text, and creating the storage arrays at full size from the start in
order to avoid using append(). Append() causes the interpreter to dynamically
increase the array's size as needed, which is slower.
from collections import defaultdict
# Create zero-filled sim1, sim2, sim3 arrays to avoid append() overhead
len_ = len(db[2]) - 2
for _ in range(3):
db.append([0] * len_)
# Create dictionary, containing d['word'] = [count, [indexes]]
# Do just one full iteration, and make good use of it by calculating
# sim1 (as 'count') and storing an array of number indexes for each word,
# allowing for a very efficient loop coming up...
d = defaultdict(lambda: [0, []])
for index, word in enumerate(db[2]):
if index < len_:
# Accumulate sim1
d[word][0] += 1
# Store all db[2] indexes where this word exists
d[word][1].append(index)
# Now loop only through words which occur more than once (smaller loop)
for word, (count, indexes) in d.iteritems():
if count > 1:
# Place the sim1 values into the db[3] array
for i in indexes:
if i < len_:
db[3][i] = count - 1
# Look for sim2 matches by using index numbers
next_word = db[2][i+1]
for next_word_index in d[next_word][1]:
if next_word_index - 1 != i and next_word_index - 1 in indexes:
# Accumulate sim2 value in db[4]
db[4][i] += 1
# Look for sim3 matches
third_word = db[2][i+2]
if third_word == db[2][next_word_index + 1]:
# Accumulate sim3 value in db[5]
db[5][i] += 1
|
What does translate mean in pypy?
Question: I'm reading [pypy's document](http://doc.pypy.org/en/latest/getting-started-
python.html), which has a section called _Translating the PyPy Python
interpreter_. But i don't understand what does the word _translate_ mean. Is
it the same as _compile_?
The document says:
> First download a pre-built PyPy for your architecture which you will use to
> translate your Python interpreter.
Is the **pre-built PyPy** here refer to the source code? Because there is no
pypy/goal directory in the binary I have downloaded. If so, there is something
wrong with the document. It is misleading.
Is the pypy-c created in the translation the same thing as bin/pypy in the
binary?
Answer: > i don't understand what does the word translate mean. Is it the same as
> compile?
What "translation" means is described in detail in [The RPython
Toolchain](http://doc.pypy.org/en/latest/translation.html). There's also some
higher-level introductory information in the [Coding
Guide](http://doc.pypy.org/en/latest/coding-guide.html) and
[FAQ](http://doc.pypy.org/en/latest/faq.html).
Summarizing their summary:
1. Compile and import the complete RPython program.
2. Dynamically analyze the program and annotate it with flow graphs.
3. Compile the flow graphs into lower-level flow graphs.
4. Optimize the compiled flow graphs.
5. Analyze the compiled and optimized flow graphs.
6. Generate C source from the flow graphs and analysis.
7. Compile and link the C source into a native executable.
So, step 1 uses the normal Python compiler, step 7 uses the normal C compiler
(and linker), and steps 3 and 4 are similar to the kind of thing an optimizing
compiler normally does. But calling the overall process "compilation" would be
misleading. (Also, people would probably interpret it to mean something akin
to what Shedskin does, which is definitely not right.)
> Is the pypy-c created in the translation the same thing as bin/pypy in the
> binary?
What ends up in a binary distribution is basically the same as if you run the
install process on the translation goal. So, yes, `goal/pypy-c` and `bin/pypy`
are effectively the same thing.
> Is the pre-built PyPy here refer to the source code?
No. It refers to a `bin/pypy` from a binary distribution. As the docs say, you
can actually use _any_ Python 2.6+, including CPython, or a `goal/pypy-c` left
over from a previous build, etc. However, the translator will probably run
fastest on the standard PyPy binary distribution, so that's what you should
use unless you have a good reason to do otherwise.
|
What is the init function of a dynamic module in python?
Question: I am getting the same error of these other two questions: [ImportError:
dynamic module does not define init function, but it
does](http://stackoverflow.com/questions/5041861/importerror-dynamic-module-
does-not-define-init-function-but-it-does) and [Cython compiled C extension:
ImportError: dynamic module does not define init
function](http://stackoverflow.com/questions/8024805/cython-compiled-c-
extension-importerror-dynamic-module-does-not-define-init-fu)
But their solutions are not equal, and didn't work for me as well.
I am trying to call functions of a shared library that I have wrote in c,
inside my python program.
I compiled my shared lib like this:
gcc -shared -Wl,-soname,playfaircrack.so -o playfaircrack.so -fPIC playfaircrack.c scoreText.o
I created a module, and inside this module I load this lib with:
cracker = ctypes.cdll.LoadLibrary('./playfaircrack.so')
But when I run the code, I get the following error:
Traceback (most recent call last):
File "playfair.py", line 2, in <module>
import playfaircrack
ImportError: dynamic module does not define init function (initplayfaircrack)
Which is very strange, because if I run the python interpreteer, and call
directly:
cracker = ctypes.cdll.LoadLibrary('./playfaircrack.so')
I can access the functions of my shared lib.
Any ideas how to solve this? Thank you.
Answer: Delete the line
import playfaircrack
in `playfair.py` and it should work.
Alternatively, rename `playfaircrack.so` to something else or moved it to a
different directory. Python gets confused if you have two files with the same
module name, i.e. `playfaircrack.py` and `playfaircrack.so` in the same
directory. Python tries to import `playfaircrack.so`, which is no valid Python
module, before it gets to `playfaircrack.py`.
|
SQL parsing using pyparsing
Question: I am learning PyParsing in last few weeks. I plan to use it to get table names
from SQL statements. I have looked at
<http://pyparsing.wikispaces.com/file/view/simpleSQL.py>. But I intend to keep
the grammar simple because I am not trying to get every part of select
statement parsed rather I am looking for just table names. Also it is quite
involved to define the complete grammar for any commercially available modern
day database like Teradata.
#!/usr/bin/env python
from pyparsing import *
import sys
semicolon = Combine(Literal(';') + lineEnd)
comma = Literal(',')
lparen = Literal('(')
rparen = Literal(')')
# Keyword definition
update_kw, volatile_kw, create_kw, table_kw, as_kw, from_kw, \
where_kw, join_kw, left_kw, right_kw, cross_kw, outer_kw, \
on_kw , insert_kw , into_kw= \
map(lambda x: Keyword(x, caseless=True), \
['UPDATE', 'VOLATILE', 'CREATE', 'TABLE', 'AS', 'FROM',
'WHERE', 'JOIN' , 'LEFT', 'RIGHT' , \
'CROSS', 'OUTER', 'ON', 'INSERT', 'INTO'])
# Teradata SQL allows SELECT and well as SEL keyword
select_kw = Keyword('SELECT', caseless=True) | Keyword('SEL' , caseless=True)
# list of reserved keywords
reserved_words = (update_kw | volatile_kw | create_kw | table_kw | as_kw |
select_kw | from_kw | where_kw | join_kw |
left_kw | right_kw | cross_kw | on_kw | insert_kw |
into_kw)
# Identifier can be used as table or column names. They can't be reserved words
ident = ~reserved_words + Word(alphas, alphanums + '_')
# Recursive definition for table
table = Forward()
# simple table name can be identifer or qualified identifier e.g. schema.table
simple_table = Combine(Optional(ident + Literal('.')) + ident)
# table name can also a complete select statement used as table
nested_table = lparen.suppress() + select_kw.suppress() + SkipTo(from_kw).suppress() + \
from_kw.suppress() + table + rparen.suppress()
# table can be simple table or nested table
table << (nested_table | simple_table)
# comma delimited list of tables
table_list = delimitedList(table)
# Building from clause only because table name(s) will always appears after that
from_clause = from_kw.suppress() + table_list
txt = """
SELECT p, (SELECT * FROM foo),e FROM a, d, (SELECT * FROM z), b
"""
for token, start, end in from_clause.scanString(txt):
print token
A thing worth mentioning here. I use "SkipTo(from_kw)" to jump over column
list in SQL statement. This is primarily to avoid defining grammar for column
list which can be comma delimited list of identifiers, many function names, DW
analytical functions and what not. With this grammar I am able to parse above
statement as well as any level of nesting in SELECT column list or table list.
['foo']
['a', 'd', 'z', 'b']
I am facing problem when SELECT has where clause:
nested_table = lparen.suppress() + select_kw.suppress() + SkipTo(from_kw).suppress() + \
from_kw.suppress() + table + rparen.suppress()
When WHERE clause is there then the same statement may look like: SELECT ...
FROM a,d , (SELECT * FROM z WHERE (c1 = 1) and (c2 = 3)), p I thought of
changing "nested_table" definition to:
nested_table = lparen.suppress() + select_kw.suppress() + SkipTo(from_kw).suppress() + \
from_kw.suppress() + table + Optional(where_kw + SkipTo(rparen)) + rparen
But this is not working since it matches to the right parenthesis following "c
= 1". What I would like to know is how to skip to the right parenthesis that
matches left parenthesis right before "SELECT * FROM z..." I don't know how to
do it using PyParsing
Also on a different note I seek some advice the best way to get table names
from complex nested SQLs. Any help is really appreciated.
Thanks Abhijit
Answer: Considering that you are also trying to parse out nested SELECT's, I don't
think you'll be able to avoid writing a fairly complete SQL parser.
Fortunately, there is a more complete example on the Pyparsing wiki Examples
page,
[select_parser.py](http://pyparsing.wikispaces.com/file/view/select_parser.py/158651233/select_parser.py).
I hope that gets you further along.
|
How to define start and end times in python
Question: I am using the code
def run_periodically(start, end, interval, func):
event_time = start
while event_time < end:
s.enterabs(event_time, 0, func, ())
event_time += interval + random(-5, 45)
s.run()
run_periodically(time()+5, time()+1000000, 10, getData)
Now If I wanted to define the start time as 22.00 how is this formatted in
python?
e.g. I would change the code to
starttime = #?#
run_periodically(starttime(), time()+1000000, 10, getData)
What is the standard time formatting used to make this work?
Answer: The Python time() related functions take the number of seconds since a
particular date (depending on your os). You can convert that from the
`datetime` types using `datetime.time()`
import datetime
timestamp = datetime.datetime(2013, 6, 4, 6, 18, 1).time()
That makes `timestamp` usable for `run_periodically`.
You can also go the other way by using `datetime.fromtimestamp(time.time())`.
All this and more detailed info can be found in the [module
documentation](http://docs.python.org/2/library/datetime.html).
|
Python: return files in directory and subdirectory
Question: Trying to create a function that returns the # of files found a directory and
its subdirectories. Just need help getting started
Answer: One - liner
import os
cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])
|
How do I create a module for a fibonacci sequence in Python on a Mac with TextWrangler?
Question: I've been trying to search up valid sequences online but haven't come across
one that works in Python interpreter. Every time I input a sequence, the
interpreter always finds some sort of mistake or is not able to formulate a
module specific to it that I can import. Along with that, I have not been able
to find a downloadable version of the module for Mac.
I've used several sequences. Maybe there are numbers I must input in addition
to it? I've been using this sequences in raw form, copying and pasting from a
website to TextWrangler:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
I am trying to use an importable version in order to solve Project Euler's
problem number 2. I'm a beginner and interested in learning more about
programming in order to pursue computational sciences.
Answer: Put this in a file named `fibonacci.py`:
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Then open an other file `__main__.py` in the same folder as `fibonacci.py`.
The content of `__main__.py` should be:
import fibonacci
print(fibonacci.fib(3))
Then you can execute the `__main__.py` file and it should work.
|
Python script to run background services over SSH
Question: Summary: I am ssh'ing to a remote server and executing a fork1.py script over
there which is shown below. But the trouble is that I want the processes to
execute in the background, so that I can start multiple services. I know we
can use nohup, etc. but they are not working. Even when I use a & at the end,
the process starts, but gets killed when the script terminates.
Here is the code:
import os
import sys
import commands
from var import key_loc
import subprocess
import pipes
import shlex
def check(status):
if status != 0:
print 'Error! '
quit()
else:
print 'Success :) '
file1=open('/home/modiuser/status.txt','a')
file1.write("Success :)\n")
if(sys.argv[1]=="ES"):
os.chdir('/home/modiuser/elasticsearch-0.90.0/bin/')
proc1=subprocess.Popen(shlex.split("nohup ./elasticsearch -p /home/modiuser/es.pid"))
if(sys.argv[1]=="REDIS"):
os.chdir('/home/modiuser/redis-2.6.13/src')
proc2=subprocess.Popen(shlex.split("./redis_ss -p /home/modiuser/redis.pid"))
if(sys.argv[1]=="PARSER"):
proc3=subprocess.Popen(shlex.split("nohup java -jar logstash-1.1.12-flatjar.jar agent -f parser.conf"))
file1=open('/home/modiuser/pid.txt','a')
file1.write("PARSER-"+str(proc3.pid)+"\n")
file1.write(str(proc3.poll()))
file1.close()
if(sys.argv[1]=="SHIPPER_TCP"):
proc4=subprocess.Popen(shlex.split("nohup java -jar logstash-1.1.12-flatjar.jar agent -f shipper_TCP.conf"))
file1=open('/home/modiuser/pid.txt','a')
file1.write("SHIPPER_TCP-"+str(proc4.pid)+"\n")
file1.close()
Where am I going wrong?
Answer: just try with
import os
os.system('python program1.py &') #this one runs in the background
os.system('python program2.py') #this one runs in the foreground
|
Why am I getting an apache server error page on a django vhost using underscore in my subdomain?
Question: I'm using django 1.5.0 and apache 2.2.22. I can't seem to get my site running
as a named vhost (I've got other django sites already running fine on this
server).
I'm getting the standard apache 500 error page. My error log suggests that've
I've got a problem with my ALLOWED_HOSTS setting -
[Tue Jun 04 10:25:22 2013] [error] [client 31.52.39.247] SuspiciousOperation: Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): sub_domain.mydomain.com
But my `ALLOWED_HOSTS` setting looks ok to me -
python manage.py shell
>> from django.conf import settings
>> settings.ALLOWED_HOSTS
['sub_domain.mydomain.com', 'livedomain.com']
Also - I don't know why I'm getting the apache 500 page rather than the django
debug page -
>> settings.DEBUG
True
Looking at the full stack trace in the error log, I can see that the wsgi app
is running - it's definitely running django code.
Any suggestions?
Answer: Firstly, `ALLOWED_HOSTS` should be ignored altogether when you have
`DEBUG=True` so that's strange that you are getting validation errors.
I was having an issue similar to this with nginx where I had an underscore in
my host name which meant Django didn't validate it. This might be an issue
particularly if you are having Apache rewriting your host header (this was the
case for me as nginx was reverse proxying) or your subdomain includes an `_`.
[You can see how Django validates hostnames in the
source](https://github.com/django/django/blob/master/django/http/request.py#L27),
furthermore, [I wrote a quick blog post on
this](http://timmyomahony.com/blog/2013/04/24/suspiciousoperation-invalid-
http_host-header-django/) also which might help
|
Call functions in PyDev Eclipse in form generated by Qt Designer
Question: python version 3.3.2
ide: PyDev Eclipse with PyQt installed
I designed a gui in Qt Designer, saved the .ui file and convert it into python
code with this command:
pyuic4 -x DeA.ui -o DeA.py

Qt Designer xml output:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>485</width>
<height>374</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="btn_add">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>121</width>
<height>41</height>
</rect>
</property>
<property name="text">
<string>Add item</string>
</property>
</widget>
<widget class="QListView" name="lst">
<property name="geometry">
<rect>
<x>10</x>
<y>60</y>
<width>461</width>
<height>301</height>
</rect>
</property>
</widget>
</widget>
</widget>
<resources/>
<connections/>
</ui>
pyuic4 final python gui output:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'DeA.ui'
#
# Created: Tue Jun 4 03:30:45 2013
# by: PyQt4 UI code generator 4.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(485, 374)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.btn_add = QtGui.QPushButton(self.centralwidget)
self.btn_add.setGeometry(QtCore.QRect(10, 10, 121, 41))
self.btn_add.setObjectName(_fromUtf8("btn_add"))
self.lst = QtGui.QListView(self.centralwidget)
self.lst.setGeometry(QtCore.QRect(10, 60, 461, 301))
self.lst.setObjectName(_fromUtf8("lst"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.btn_add.setText(_translate("MainWindow", "Add item", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
then I copy and paste the content of newly created python file(“DeA.py”) into
my python file in PyDev Eclipse and hit Run, and gui shows up just fine;

**my questions:**
where exactly in PyDev Eclipse script pane (not using slots in Qt Designer)
can I add my own python functions so that when I hit the “Add item” button, it
adds 100 items into the ListView?
I found this question: [Linking a qtDesigner .ui file to
python/pyqt?](http://stackoverflow.com/questions/2398800/linking-a-qtdesigner-
ui-file-to-python-pyqt) about linking the .ui file into the final project and
build gui at run time; but I couldn’t understand it; Please help; what exactly
should I add into my PyDev Eclipse script pane to link the .ui file and build
it at runtime? (suppose the .ui file path is: D:\DeA.ui)
Answer: you do not have to actually convert the .ui file to .py to use it, you can do
something like this..
lest say that my .ui file is
"C:/mydesign.ui"
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4 import uic
import sys
FORM_1, BASE_1 = uic.loadUiType(r"C:/mydesign.ui")
APP = QtGui.QApplication(sys.argv)
class MyApp(FORM_1, BASE_1):
def __init__(self, parent=None):
super(MyApp, self).__init__(parent)
self.setupUi(self)
self.connect(self.btn_add, QtCore.SIGNAL("released()"), self.do_something)
def do_something(self):
print "working"
FORM = MyApp()
FORM.show()
APP.exec_()
|
Code window for websites
Question: I am the webmaster from [www.idoodler.de](http://www.idoodler.de), I started a
Raspberry Pi how to site. The site contains Python, Ruby, Shell Script…
scripts. My question: Is is there a HTML code that formats the code like in
Stackoverflow?
Like this:
import os
os.system(command)
it would be even better if the window can add colors to the different types of
code.
It would be very cool if someone can tell me either how to make such a HTML
view or a link to a site that explains how to achieve this. And btw I am using
Sandvox for Mac to create the website, so I am able to use Sandvox plugins
too.
Thanks David from Germany
Answer: For highlighting code in HTML you can use
[highlight.js](http://softwaremaniacs.org/soft/highlight/en/). All you have to
do is wrap your code in `<pre><code>` tags and include the JS file:
<pre><code> some code in here </code></pre>
Highlight.js will then try to recognize, which language was used and apply the
highlighting accordingly.
|
How to test command line scripts with nose?
Question: I've created a Python library with some command-line scripts in a 'bin'
directory (so that `setup.py` will install it into 'bin' when installing it
with `pip`). Since this isn't a Python module, I can't work out how to test it
with nose.
How can I test a command line script that's part of a library using
`nose`/`unittest`?
Answer: Use the "[`if __name__ ==
"__main__":`](http://stackoverflow.com/questions/419163/what-does-if-name-
main-do)" idiom in your scripts and encapsulate _all of_ the _function_ -ality
in _function_ -s.
Then you can `import` your scripts into another script (such as a unit test
script) without the body of it being executed. This will allow you to write
unit-tests for the functionality and run them through `nose`.
I recommend keeping the "main" block to a line or two.
## For example:
### plus_one.py
#!/usr/bin/env python
import sys
def main(args):
try:
output(plus_one(get_number(args)))
except (IndexError, ValueError), e:
print e
return 1
return 0
def get_number(args):
return int(args[1])
def plus_one(number):
return number + 1
def output(some_text):
print some_text
if __name__ == '__main__':
sys.exit(main(sys.argv))
You can test command-line parameters, output, exceptions and return codes in
your unittests...
### t_plus_one.py
#!/usr/bin/env python
from StringIO import StringIO
import plus_one
import unittest
class TestPlusOne(unittest.TestCase):
def test_main_returns_zero_on_success(self):
self.assertEquals(plus_one.main(['test', '1']), 0)
def test_main_returns_nonzero_on_error(self):
self.assertNotEqual(plus_one.main(['test']), 0)
def test_get_number_returns_second_list_element_as_integer(self):
self.assertEquals(plus_one.get_number(['anything', 42]), 42)
def test_get_number_raises_value_error_with_string(self):
self.assertRaises(ValueError, plus_one.get_number, ['something',
'forty-two'])
def test_get_number_raises_index_error_with_too_few_arguments(self):
self.assertRaises(IndexError, plus_one.get_number, ['nothing'])
def test_plus_one_adds_one_to_number(self):
self.assertEquals(plus_one.plus_one(1), 2)
def test_output_prints_input(self):
saved_stdout, plus_one.sys.stdout = plus_one.sys.stdout, StringIO('_')
plus_one.output('some_text')
self.assertEquals(plus_one.sys.stdout.getvalue(), 'some_text\n')
plus_one.sys.stdout = saved_stdout
if __name__ == '__main__':
unittest.main()
## Output
### `python plus_one.py 41`
42
### `nosetests -v t_plus_one.py`
test_get_number_raises_index_error_with_too_few_arguments (t_plus_one.TestPlusOne) ... ok
test_get_number_raises_value_error_with_string (t_plus_one.TestPlusOne) ... ok
test_get_number_returns_second_list_element_as_integer (t_plus_one.TestPlusOne) ... ok
test_main_returns_nonzero_on_error (t_plus_one.TestPlusOne) ... ok
test_main_returns_zero_on_success (t_plus_one.TestPlusOne) ... ok
test_output_prints_input (t_plus_one.TestPlusOne) ... ok
test_plus_one_adds_one_to_number (t_plus_one.TestPlusOne) ... ok
----------------------------------------------------------------------
Ran 7 tests in 0.002s
OK
|
How to push into array nested in dictionary?
Question: I want to create a mongodb to store the homework results, I create a
`homework` which is a dictionary storing the results' array of each subject.
import pymongo
DBCONN = pymongo.Connection("127.0.0.1", 27017)
TASKSINFO = DBCONN.tasksinfo
_name = "john"
taskid = TASKSINFO.tasksinfo.insert(
{"name": _name,
"homework": {"bio": [], "math": []}
})
TASKSINFO.tasksinfo.update({"_id": taskid},
{"$push": {"homework.bio", 92}})
When I tried to push some information to db, there's error:
Traceback (most recent call last):
File "mongo_push_demo.py", line 13, in <module>
{"$push": {"homework.bio", 92}})
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/pymongo/collection.py", line 479, in update
check_keys, self.__uuid_subtype), safe)
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/pymongo/message.py", line 110, in update
encoded = bson.BSON.encode(doc, check_keys, uuid_subtype)
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/bson/__init__.py", line 567, in encode
return cls(_dict_to_bson(document, check_keys, uuid_subtype))
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/bson/__init__.py", line 476, in _dict_to_bson
elements.append(_element_to_bson(key, value, check_keys, uuid_subtype))
File "/usr/local/lib/python2.7/dist-packages/pymongo-2.5-py2.7-linux-i686.egg/bson/__init__.py", line 466, in _element_to_bson
type(value))
bson.errors.InvalidDocument: cannot convert value of type <type 'set'> to bson
Answer:
{"$push": {"homework.bio", 92}})
It should be `:`, not `,`.
`{'a', 1}` is a set of two elements in Python, that's why you get the error.
|
Python: Pause for-loop while application closes
Question: I have a script that I would like to bulk edit powerpoint files with. If I
edit files one by one with it, it works great. If I bulk edit them, it fails.
I assume this is because the application is not closing before the next file
attempts to load, but I could, and most likely am, wrong.
The code:
import win32com.client, sys, glob
folder = (glob.glob('*.ppt'))
print("="*20)
print(folder)
print("="*20)
if folder:
for files in folder:
print("Current File: " + files)
try:
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
Presentation = Application.Presentations.Open("c:/pptpy/testfolder/" + files)
for Slide in Presentation.Slides:
for Shape in Slide.Shapes:
try:
Shape.TextFrame.TextRange.Font.Name = "Arial"
Shape.TextFrame.TextRange.Font.Size = "14"
Shape.TextFrame.TextRange.Font.Color.RGB = "000000"
except:
pass
Presentation.Save()
Application.Quit()
#Adding a time.sleep(1) here pauses the Application.Quit()
except:
print("Error in: " + files)
pass
The error (when not passing exceptions):
Traceback (most recent call last):
File "C:\pptpy\testfolder\convert.py", line 19, in <module>
for Shape in Slide.Shapes:
File "C:\Python33\lib\site-packages\win32com\client\dynamic.py", line 247, in __getitem__
return self._get_good_object_(self._enum_.__getitem__(index))
File "C:\Python33\lib\site-packages\win32com\client\util.py", line 37, in __getitem__
return self.__GetIndex(index)
File "C:\Python33\lib\site-packages\win32com\client\util.py", line 53, in __GetIndex
result = self._oleobj_.Next(1)
pywintypes.com_error: (-2147023174, 'The RPC server is unavailable.', None, None)
Details:
Python3.3
Powerpoint2007
If you need any more details, I would be happy to provide them! Thanks!
Answer: Try something like this (building on previous
[question](http://stackoverflow.com/questions/16915067/powerpoint-python-
editing-ppt-fails-when-an-image-is-reached)). You should really invest time in
designing your code before you ask questions like this:
import win32com.client
import sys # <- obsolete not used
import os
import glob # style guide one import per line
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
ppt_files = glob.glob('*.ppt')
for file in ppt_files:
file = os.path.abspath(file)
Presentation = Application.Presentations.Open(file)
for Slide in Presentation.Slides:
for Shape in Slide.Shapes:
try:
Shape.TextFrame.TextRange.Font.Name = "Arial"
Shape.TextFrame.TextRange.Font.Size = "12"
Shape.TextFrame.TextRange.Font.Color.RGB = "000000"
except:
pass
Presentation.Save()
Presentation.Close()
Application.Quit()
|
Building a GeoJSON with Python
Question: I want to generate dinamically a geoJSON with a variable number of polygons.
Example for 2 polygons:
{
"type": "FeatureCollection",
"features": [
{"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Polygon",
"coordinates":
[[11.0878902207, 45.1602390564],
[0.8251953125, 41.0986328125],
[7.63671875, 48.96484375],
[15.01953125, 48.1298828125]]
},
{
"type": "Polygon",
"coordinates":
[[11.0878902207, 45.1602390564],
[14.931640625, 40.9228515625],
[11.0878902207, 45.1602390564]]
}
]
},
"type": "Feature",
"properties": {}}
]
}
I have a function which gives me the list of coordinates for each polygon, so
I can create a list of polygons, so I am able to build the geoJSON iterating
it with a for loop.
The problem is that I don't see how to do it easily (I thought for example in
returning the list as a string, but building the geoJSON as a string looks
like a bad idea).
I have been suggested this very pythonic idea:
geo_json = [ {"type": "Feature",,
"geometry": {
"type": "Point",
"coordinates": [lon,lat] }}
for lon,lat in zip(ListOfLong,ListOfLat) ]
But since I am adding a variable number of Polygons instead of a list of
points, this solutions does not seem suitable. Or at least I don't know how to
adapt it.
I could build it as a string, but I'd like to do it in a smarter way. Any
idea?
Answer: There is the python-geojson library (<https://github.com/frewsxcv/python-
geojson>), which seems to make this task also much easier. Example from the
library page:
>>> from geojson import Polygon
>>> Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
{"coordinates": [[[2.3..., 57.32...], [23.19..., -20.2...], [-120.4..., 19.1...]]], "type": "Polygon"}
|
ASP.NET equivalent to Python's os.system([string])
Question: I have an app made in Python, which accesses a Linux server's command prompt
with `os.system([string])`
Now I'd like to transfer this away from Python, into some language like
ASP.NET or something.
Is there a way to access the server's command prompt and run commands with
ASP.NET or any technology found in Visual Studio?
This needs to run in a web app, where a user will click a button, and then a
server-side command will run, so it's important that the technology suggested
is compatible with all that.
Answer: Well it isn't ASP.net specific but in c#:
using System.Diagnostics;
Process.Start([string]);
Or With more access to the specific parts of running a program (like
arguments, and output streams)
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c dir *.cs";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
here is how you could combine this with an ASPx Page:
First Process.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Process.aspx.cs" Inherits="com.gnld.web.promote.Process" %>
<!DOCTYPE html>
<html>
<head>
<title>Test Process</title>
<style>
textarea { width: 100%; height: 600px }
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="RunCommand" runat="server" Text="Run Dir" onclick="RunCommand_Click" />
<h1>Output</h1>
<asp:TextBox ID="CommandOutput" runat="server" ReadOnly="true" TextMode="MultiLine" />
</form>
</body>
</html>
Then the code behind:
using System;
namespace com.gnld.web.promote
{
public partial class Process : System.Web.UI.Page
{
protected void RunCommand_Click(object sender, EventArgs e)
{
using (var cmd = new System.Diagnostics.Process()
{
StartInfo = new System.Diagnostics.ProcessStartInfo()
{
FileName = "cmd.exe",
Arguments = "/c dir *.*",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
}
})
{
cmd.Start();
CommandOutput.Text = cmd.StandardOutput.ReadToEnd();
};
}
}
}
|
Find top-level directory from subdirectory on Linux in Python
Question: I am creating various HTML file parts, image thumbnails etc. from within a
`CodeIgniter` application tree using cron-scheduled `Python 2.7` programs on
Linux. The actual Python programs exist under the `CodeIgniter` tree in a
subdirectory one level below the application directory as follows.
codeigniter/web-root
|
application
| |
| scripts
| | |
| | my-program.py
| |
| database
| |
| database.sqlite
images
I want to determine the `codeigniter/web-root` directory from within `my-
program.py` using methods from the `os.path` module. However, the absolute
path to the `codeigniter/web-root` is different on the development and
production environments so I prefer not to hardwire this path information into
the Python program itself.
The current script(s) use the following construct to determine the absolute
path of "codeigniter/web-root" which is two directory levels above the script
itself in both environments.
#!/bin/env python2.7
import os.path
ci_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Is there a cleaner way to determine the top level(ci_root) directory without
using multiple `os.path.dirname` calls?
Answer:
import os.path
print os.path.abspath(__file__+'/../../..') # the directory three levels up
I was pleasantly surprised that
* abspath() managed to parse correctly, without using os.path.join()
* We didn't have to strip out the filename before we build the path
For cross platform compatibility if abspath's parsing does not work, we could
use something less readable, e.g.
* os.path.sep instead of '/'
* os.path.join()
|
Passing values and calling functions from other functions
Question: I have this class that consists of 3 functions. Each function is in charge of
one part of the whole process.
`.load()` loads up two files, re-formats their content and writes them to two
new files.
`.compare()` takes two files and prints out their differences in a specific
format.
`.final()` takes the result of `.compare()` and creates a file for every set
of values.
Please ignore the Frankenstein nature of the logic as it is not my main
concern at the moment. I know it can be written a thousand times better and
that's fine by me for now as i am still new to Python and programing in
general. I do have some theoretical experience but very limited technical
practice and that is something i am working on.
Here is the code:
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
from collections import deque
import os
class avs_auto:
def load(self, fileIn1, fileIn2, fileOut1, fileOut2):
with open(fileIn1+'.txt') as fin1, open(fileIn2+'.txt') as fin2:
frame_rects = defaultdict(list)
for row in (map(str, line.split()) for line in fin1):
id, frame, rect = row[0], row[2], [row[3],row[4],row[5],row[6]]
frame_rects[frame].append(id)
frame_rects[frame].append(rect)
for row in (map(str, line.split()) for line in fin2):
id, frame, rect = row[0], row[2], [row[3],row[4],row[5],row[6]]
frame_rects[frame].append(id)
frame_rects[frame].append(rect)
with open(fileOut1+'.txt', 'w') as fout1, open(fileOut2+'.txt', 'w') as fout2:
for frame, rects in sorted(frame_rects.iteritems()):
fout1.write('{{{}:{}}}\n'.format(frame, rects))
fout2.write('{{{}:{}}}\n'.format(frame, rects))
def compare(self, f1, f2):
with open(f1+'.txt', 'r') as fin1:
with open(f2+'.txt', 'r') as fin2:
lines1 = fin1.readlines()
lines2 = fin2.readlines()
diff_lines = [l.strip() for l in lines1 if l not in lines2]
diffs = defaultdict(list)
with open(f1+'x'+f2+'Result.txt', 'w') as fout:
for line in diff_lines:
d = eval(line)
for k in d:
list_ids = d[k]
for i in range(0, len(d[k]), 2):
diffs[d[k][i]].append(k)
for id_ in diffs:
diffs[id_].sort()
for k, g in groupby(enumerate(diffs[id_]), lambda (i, x): i - x):
group = map(itemgetter(1), g)
fout.write('{0} {1} {2}\n'.format(id_, group[0], group[-1]))
def final(self):
with open('hw1load3xhw1load2Result.txt', 'r') as fin:
lines = (line.split() for line in fin)
for k, g in groupby(lines, itemgetter(0)):
fst = next(g)
lst = next(iter(deque(g, 1)), fst)
with open('final/{}.avs'.format(k), 'w') as fout:
fout.write('video0=ImageSource("MovieName\original\%06d.jpeg", {}, {}, 15)\n'.format(fst[1], lst[2]))
Now to my question, how do i make it so each of the functions passes it's
output files as values to the next function and calls it?
So for an example:
running `.load()` should output two files, call the `.compare()` function
passing it those two files.
Then when `.compare()` is done, it should pass `.final()` the output file and
calls it.
So `.final()` will open whatever file is passed to it from `.compare()` and
not `"test123.txt"` as it is defined above.
I hope this all makes sense. Let me know if you need clarification. Any
criticism is welcome concerning the code itself. Thanks in advance.
Answer: Do you mean call with the name of the two files? Well you defined a class, so
you can just do:
def load(self, fileIn1, fileIn2, fileOut1, fileOut2):
... // do stuff here
// when done
self.compare( fileOut1, fileOut2 )
And so on.
|
Python: split on either a space or a hyphen?
Question: In Python, how do I split on either a space or a hyphen?
Input:
You think we did this un-thinkingly?
Desired output:
["You", "think", "we", "did", "this", "un", "thinkingly"]
I can get as far as
mystr.split(' ')
But I don't know how to split on hyphens as well as spaces [and the Python
definition of split only seems to specify a
string](http://docs.python.org/2/library/stdtypes.html). Do I need to use a
regex?
Answer:
>>> import re
>>> text = "You think we did this un-thinkingly?"
>>> re.split(r'\s|-', text)
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
As @larsmans noted, to split by multiple spaces/hyphens (emulating `.split()`
with no arguments) used `[...]` for readability:
>>> re.split(r'[\s-]+', text)
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
Without regex (regex is the most straightforward option in this case):
>>> [y for x in text.split() for y in x.split('-')]
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
Actually the answer by [@Elazar](http://stackoverflow.com/a/16926952/1219006)
without regex is quite straightforward as well (I would still vouch for regex
though)
|
Concurrent control of generator and subroutine in Python
Question: Function `bigop(init, report)` operates on a large dynamic internal data
structure `data` derived from `init`, and accepts a callable `report(data)`.
Function `status(data)` returns a summary of the current state of `data`.
Function `bigop` calls `report` on the current state of `data` at each major
step, which in turn calls `status`. It would be expensive to copy `data` for
each step (or make it persistent), so `report` must finish at each step before
`bigop` continues.
Function `view(gen)` accepts a generator `gen` yielding successive values of
the status summary, and displays a visualization of each value as it is
generated. The function `view` maintains internal state dependent on values
generated thus far. (In my particular case, this internal state _could_ be
copied, but it would be nice to avoid.)
Assume that functions `bigop` and `view` cannot be changed.
Question: how can one define `gen`, `report`, and a program `main` such that
`bigop` will run on `init`, and visualizations of the values of the status
reports will be displayed _as_ `bigop` reaches each major step?
The difficulty lies in that `report` and `gen` are called inside other
functions, so the usual Python coroutine patterns are inapplicable. (In my
particular case, `bigop` is actually a generator.)
[A previous question](http://stackoverflow.com/questions/9968592/turn-
functions-with-a-callback-into-python-generators?rq=1) about using callbacks
to produce generators from ordinary functions was answered using threads, but
I am wondering if there is a simpler way.
Note: only answers compatible with Python 2.7 will be useful to me; but I
would be interested to see Python 3 answers if the differences are relevant.
def bigop(init, report):
data = init
while data < 10: # complicated condition
print 'working ...'
data += 1 # complicated operation
report(data)
def view(gen):
for value in gen:
print value # complicated display routine
def main(init):
"""
example:
>> main(7)
'working ...'
8
'working ...'
9
'working ...'
10
"""
pass
Question: how to define `main`?
Answer: Given your sample code:
def main(init):
def report(x):
print x
bigop(init, report)
However, I don't think that's what you're looking for here. Presumably you
want `report` to feed data into `view` in some way.
You can do that by turning things around—instead of `view` being a generator
that drives another generator, it's a generator that's driven by an outside
caller calling `send` on it. For example:
def view():
while True:
value = yield
print value
def main(init):
v = view()
v.next()
def report(x):
v.send(x)
bigop(init, report)
But you said that `view` can't be changed. Of course you can write a
`viewdriver` that `yield`s a new object whenever you `send` it one. Or, more
simply, just repeatedly call `view([data])` and let it iterate over a single
object.
Anyway, I don't see how you expect this to help anything. `bigop` is not a
coroutine, and you cannot turn it into one. Given that, there's no way to
force it to cooperatively share with other coroutines.
If you want to interleave processing and reporting concurrently, you have to
use threads (or processes). And the fact that "REPORT must finish at each step
before BIGOP continues" is already part of your requirements implies that you
can't safely do anything concurrent here anyway, so I'm not sure what you're
looking for.
If you just want to interleave processing and reporting _without_
concurrency—or periodically hook into `bigop`, or other similar things—you
_can_ do that with a coroutine, but it will have exactly the same effect as
using a subroutine—the two examples above are pretty much equivalent. So,
you're just adding complexity for no reason.
(If `bigop` is I/O bound, you could use greenlets, and monkeypatch the I/O
operations to asyncify them, as `gevent` and `eventlet` do. But if it's CPU-
bound, there would be no benefit to doing so.)
* * *
Elaborating on the `viewdriver` idea: What I was describing above was
equivalent to calling `view([data])` each time, so it won't help you. If you
want to make it an iterator, you can, but it's just going to lead to either
blocking `bigop` or spinning `view`, because you're trying to feed a consumer
with a consumer.
It may be hard to understand as a generator, so let's build it as a class:
class Reporter(object):
def __init__(self):
self.data_queue = []
self.viewer = view(self)
def __call__(self, data):
self.data_queue.append(data)
def __iter__(self):
return self
def __next__(self):
return self.data_queue.pop()
bigop(init, Reporter())
Every time `bigop` calls `report(data)`, that calls our `__call__`, adding a
new element to our queue. Every time `view` goes through the loop, it calls
our `__next__`, popping an element off the queue. If `bigop` is guaranteed to
go faster than `view`, everything will work, but the first time `view` gets
ahead, it will get an `IndexError`.
The only way to fix that is to make `__next__` try until `data_queue` is non-
empty. But just doing that will spin forever, not letting `bigop` do the work
to produce a new element. And you can't make `__next__` into a generator,
because `view` is expecting an iterator over values, not an iterator over
iterators.
Fortunately, `__call__` can be a generator, because `bigop` doesn't care what
value it gets back. So, you can turn things around. But you can't do that,
because then there's nothing to drive that generator.
So, you have to add another level of coroutines, underneath the iteration.
Then, `__next__` can wait on a `next_coro` (by calling `next` on it), which
yields to a `call_coro` and then yields the value it got. Meanwhile,
`__call__` has to `send` to the same `call_coro`, wait on it, and yield.
So far, that doesn't change anything, because you've got two routines both
trying to drive `next_coro`, and one of them (`__next__`) isn't blocking
anywhere else, so it's just going to spin—it's `next` call will look like a
`send(None)` from `__call__`.
The only way to fix that is to build a trampoline ([PEP
342](http://www.python.org/dev/peps/pep-0342/) includes source for a general-
purpose trampoline, although in this case you could build a simpler special-
purpose one), schedule `next_coro` and `call_coro` to explicitly alternate,
make sure `next_coro` properly handles alternating between two different entry
points, then drive the scheduler's `run` from `__next__` (and `__init__`).
Confused? You won't be, after this week's episode of… Nah, who am I kidding.
You're going to be confused. Writing all of this is one thing; debugging it is
another. (Especially since every important stack trace just terminates
immediately at the trampoline.) And what does all that work get you? The exact
same benefit as using greenlets or threads, with the exact same downsides.
Since your original question is whether there's a simpler way than using
threads, the answer is: No, there isn't.
|
using output of scipy.interpolate.UnivariateSpline later in python or in Matlab without needing original datapoints
Question: I'm using
[`scipy.interpolate.UnivariateSpline`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.UnivariateSpline.html)
to smoothly interpolate a large amount of data. Works great. I get an object
which acts like a function.
Now I want to save the spline points for later and use them in Matlab (and
also Python, but that's less urgent), without needing the original data. How
can I do this?
In scipy I have no clue; UnivariateSpline does not seem to offer a constructor
with the previously-computed knots and coefficients.
In MATLAB, I've tried the Matlab functions
[`spline()`](http://www.mathworks.com/help/matlab/ref/spline.html) and
`pchip()`, and while both come close, they have errors near the endpoints that
look kind of like [Gibbs ears](http://en.wikipedia.org/wiki/Gibbs_phenomenon).
Here is a sample set of data that I have, in Matlab format:
splinedata = struct('coeffs',[-0.0412739180955273 -0.0236463479425733 0.42393753107602 -1.27274336116436 0.255711720888164 1.93923263846732 -2.30438927604816 1.02078680231079 0.997156858475075 -2.35321792387215 0.667027554745454 0.777918416623834],...
'knots',[0 0.125 0.1875 0.25 0.375 0.5 0.625 0.75 0.875 0.9999],...
'y',[-0.0412739180955273 -0.191354308450615 -0.869601364377744 -0.141538578624065 0.895258135865578 -1.04292294390242 0.462652465278345 0.442550440125204 -1.03967756446455 0.777918416623834])
The coefficients and knots are the result of calling `get_coeffs()` and
`get_knots()` on the scipy UnivariateSpline. The 'y' values are the values of
the UnivariateSpline at the knots, or more precisely:
y = f(f.get_knots())
where f is my UnivariateSpline.
How can I use this data to make a spline that matches the behavior of the
UnivariateSpline, without having to use the Curve-Fitting Toolbox? I don't
need to do any data fitting in Matlab, I just need to know how to construct a
cubic spline from knots/coefficients/spline values.
Answer: In scipy, try
[scipy.interpolate.splev](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html),
which takes
> tck: a sequence ... containing the knots, coefficients, and degree of the
> spline.
Added: the following python class creates spline functions: init with (knots,
coefs, degree), then use it just like spline functions created by
`UnivariateSpline( x, y, s )`:
from scipy.interpolate import splev
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splev.html
class Splinefunc:
""" splinef = Splinefunc( knots, coefs, degree )
...
y = splinef( x ) # __call__
19june untested
"""
def __init__( self, knots, coefs, degree ):
self.knots = knots
self.coefs = coefs
self.degree = degree
def __call__( self, x ):
return splev( x, (self.knots, self.coefs, self.degree ))
|
Does Python's main thread get garbage collected when it stops?
Question: In a multi-threaded Python process I have a number of _non-daemon_ threads, by
which I mean threads which keep the main process alive even after the main
thread has exited / stopped.
My non-daemon threads hold [weak
references](http://docs.python.org/release/2.6.5/library/weakref.html#weakref.ref)
to certain objects in the main thread, but when the main thread ends (control
falls off the bottom of the file) these objects do _not_ appear to be garbage
collected, and my weak reference finaliser callbacks don't fire.
Am I wrong to expect the main thread to be garbage collected? I would have
expected that the thread-locals would be deallocated (i.e. garbage
collected)...
What have I missed?
* * *
**Supporting materials**
Output from `pprint.pprint( threading.enumerate() )` showing the main thread
has stopped while others soldier on.
[<_MainThread(MainThread, stopped 139664516818688)>,
<LDQServer(testLogIOWorkerThread, started 139664479889152)>,
<_Timer(Thread-18, started 139663928870656)>,
<LDQServer(debugLogIOWorkerThread, started 139664437925632)>,
<_Timer(Thread-17, started 139664463103744)>,
<_Timer(Thread-19, started 139663937263360)>,
<LDQServer(testLogIOWorkerThread, started 139664471496448)>,
<LDQServer(debugLogIOWorkerThread, started 139664446318336)>]
And since someone always asks about the use-case...
My network service occasionally misses its real-time deadlines (which causes a
total system failure in the worst case). This turned out to be because logging
of (important) DEBUG data would block whenever the file-system has a tantrum.
So I am attempting to retrofit a number of established specialised logging
libraries to defer blocking I/O to a worker thread.
Sadly the established usage pattern is a mix of short-lived logging channels
which log overlapping parallel transactions, and long-lived module-scope
channels which are never explicitly closed.
So I created a decorator which defers method calls to a worker thread. The
worker thread is non-daemon to ensure that all (slow) blocking I/O completes
before the interpreter exits, and holds a weak reference to the client-side
(where method calls get enqueued). When the client-side is garbage collected
the weak reference's callback fires and the worker thread knows no more work
will be enqueued, and so will exit at its next convenience.
This seems to work fine in all but one important use-case: when the logging
channel is in the main thread. When the main thread stops / exits the logging
channel is _not_ finalised, and so my (non-daemon) worker thread lives on
keeping the entire process alive.
Answer: It's a bad idea for your main thread to end without calling `join` on all non-
daemon threads, or to make any assumptions about what happens if you don't.
* * *
If you don't do anything very unusual, CPython (at least
[2.0](http://hg.python.org/cpython/file/2.0/Lib/threading.py#l457)-[3.3](http://hg.python.org/cpython/file/3.3/Lib/threading.py#l829))
will cover for you by automatically calling `join` on all non-daemon threads
as pair of `_MainThread._exitfunc`. This isn't actually documented, so you
shouldn't rely on it, but it's what's happening to you.
Your main thread hasn't actually exited at all; it's blocking inside its
`_MainThread._exitfunc` trying to `join` some arbitrary non-daemon thread. Its
objects won't be finalized until the `atexit` handler is called, which doesn't
happen until after it finishes joining all non-daemon threads.
* * *
Meanwhile, if you avoid this (e.g., by using `thread`/`_thread` directly, or
by detaching the main thread from its object or forcing it into a normal
`Thread` instance), what happens? It isn't defined. The `threading` module
makes no reference to it at all, but in CPython 2.0-3.3, and likely in any
other reasonable implementation, it falls to the [`thread`/`_thread`
module](http://docs.python.org/2/library/thread.html#module-thread) to decide.
And, as the docs say:
> When the main thread exits, it is system defined whether the other threads
> survive. On SGI IRIX using the native thread implementation, they survive.
> On most other systems, they are killed without executing try ... finally
> clauses or executing object destructors.
So, if you manage to avoid `join`ing all of your non-daemon threads, you have
to write code that can handle both having them hard-killed like daemon
threads, and having them continue running until exit.
If they do continue running, at least in CPython 2.7 and 3.3 on POSIX systems,
that the main thread's OS-level thread handle, and various higher-level Python
objects representing it, may be still retained, and not get cleaned up by the
GC.
* * *
On top of that, even if everything were released, you can't rely on the GC
ever deleting anything. If your code depends on deterministic GC, there are
many cases you can get away with it in CPython (although your code will then
break in PyPy, Jython, IronPython, etc.), but at exit time is not one of them.
CPython can, and will, leak objects at exit time and let the OS sort 'em out.
(This is why writable files that you never close may lose the last few
writes—the `__del__` method never gets called, and therefore there's nobody to
tell them to `flush`, and at least on POSIX the underlying `FILE*` doesn't
automatically flush either.)
If you want something to be cleaned up when the main thread finishes, you have
to use some kind of `close` function rather than relying on `__del__`, and you
have to make sure it gets triggered via a `with` block around the main block
of code, an `atexit` function, or some other mechanism.
* * *
One last thing:
> I would have expected that the thread-locals would be deallocated (i.e.
> garbage collected)...
Do you actually have thread locals somewhere? Or do you just mean locals
and/or globals that are only accessed in one thread?
|
Turning a python dict. to an excel sheet
Question: I am having an issue with the below code.
import urllib2
import csv
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://www.ny.com/clubs/nightclubs/index.html').read())
clubs = []
trains = ["A","C","E","1","2","3","4","5","6","7","N","Q","R","L","B","D","F"]
for club in soup.find_all("dt"):
clubD = {}
clubD["name"] = club.b.get_text()
clubD["address"] = club.i.get_text()
text = club.dd.get_text()
nIndex = text.find("(")
if(text[nIndex+1]=="2"):
clubD["number"] = text[nIndex:nIndex+15]
sIndex = text.find("Subway")
sIndexEnd = text.find(".",sIndex)
if(text[sIndexEnd-1] == "W" or text[sIndexEnd -1] == "E"):
sIndexEnd2 = text.find(".",sIndexEnd+1)
clubD["Subway"] = text[sIndex:sIndexEnd2]
else:
clubD["Subway"] = text[sIndex:sIndexEnd]
try:
cool = clubD["number"]
except (ValueError,KeyError):
clubD["number"] = "N/A"
clubs.append(clubD)
keys = [u"name", u"address",u"number",u"Subway"]
f = open('club.csv', 'wb')
dict_writer = csv.DictWriter(f, keys)
dict_writer.writerow([unicode(s).encode("utf-8") for s in clubs])
I get the error ValueError: dict contains fields not in fieldnames. I dont
understand how this could be. Any assistance would be great. I am trying to
turn the dictionary into an excel file.
Answer: `clubs` is a list of dictionaries, whereas each dictionary has four fields:
name, address, number, and Subway. You will need to encode each of the fields:
# Instead of:
#dict_writer.writerow([unicode(s).encode("utf-8") for s in clubs])
# Do this:
for c in clubs:
# Encode each field: name, address, ...
for k in c.keys():
c[k] = c[k].encode('utf-8').strip()
# Write to file
dict_writer.writerow(c)
### Update
I looked at your data and some of the fields have ending new line `\n`, so I
updated the code to encode and strip white spaces at the same time.
|
Response time for urllib in python
Question: I want to get response time when I use `urllib`. I made below code, but it is
more than response time. Can I get the time using `urllib` or have any other
method?
import urllib
import datetime
def main():
urllist = [
"http://google.com",
]
for url in urllist:
opener = urllib.FancyURLopener({})
try:
start = datetime.datetime.now()
f = opener.open(url)
end = datetime.datetime.now()
diff = end - start
print int(round(diff.microseconds / 1000))
except IOError, e:
print 'error', url
else:
print f.getcode(), f.geturl()
if __name__ == "__main__":
main()
Answer: Save yourself some hassle and use the [requests](http://docs.python-
requests.org/en/latest/user/quickstart/#response-content) module. In its
responses it provides a
[datetime.timedelta](http://docs.python.org/2/library/datetime.html) field
called 'elapsed' that lets you know how long the request took.
>>> import requests
>>> response = requests.get('http://www.google.com')
>>> print response.elapsed
0:00:01.762032
>>> response.elapsed
datetime.timedelta(0, 1, 762032)
|
Interfacing C++ and Python using SWIG
Question: I try to extend a Matrix class with SWIG to create a python interface. I used
the official Docu code. But I get a totally ridiculous error message.. It
seems to be unimportant where I declare my row class. I always get this error
while compiling. What's wrong with SWIG?
ERROR:
ANPyNetCPUPYTHON_wrap.cxx: In function ‘ANN::F2DArray ANN_F2DArray___getitem__(ANN::F2DArray*, int)’:
ANPyNetCPUPYTHON_wrap.cxx:5192: error: ‘Grid2dRow’ was not declared in this scope
ANPyNetCPUPYTHON_wrap.cxx:5192: error: expected `;' before ‘r’
ANPyNetCPUPYTHON_wrap.cxx:5193: error: ‘r’ was not declared in this scope
CODE:
%{
#include <AN2DArray.h>
%}
%include <AN2DArray.h>
%inline %{
struct Grid2dRow {
ANN::F2DArray *g; // Grid
int y; // Row number
// These functions are used by Python to access sequence types (lists, tuples, ...)
float __getitem__(int x) {
return g->GetValue(x, y);
}
void __setitem__(int x, float val) {
g->SetValue(x, y, val);
}
};
%}
%extend ANN::F2DArray
{
ANN::F2DArray __getitem__(int y) {
Grid2dRow r;
r.g = self;
r.y = y;
return r;
}
};
Answer: I found the problem after I looked into the generated *.cxx. The SWIG docu IS
wrong in two points. Below is the code which is working. Maybe someone
wondering about the same issue is helped with it.
%{
#include <AN2DArray.h>
%}
%inline %{
struct Grid2dRow {
ANN::F2DArray *g; // Grid
int y; // Row number
// These functions are used by Python to access sequence types (lists, tuples, ...)
float __getitem__(int x) {
return g->GetValue(x, y);
}
void __setitem__(int x, float val) {
g->SetValue(x, y, val);
}
};
%}
%include <AN2DArray.h>
%addmethods ANN::F2DArray {
Grid2dRow __getitem__(int y) {
Grid2dRow r;
r.g = self;
r.y = y;
return r;
}
};
|
How can I get the minimum and the maximum element of a list in python
Question: If a have a list like:
l = [1,2,3,4,5]
and I want to have at the end
min = 1
max = 5
WITHOUT `min(l)` and `max(l)`.
Answer: Loop over the list and test each item against the minimum and maximum found so
far. `float('inf')` and `float('-inf')` (infinity and negative infinity) are
good starting points to simplify the logic:
minimum = float('inf')
maximum = float('-inf')
for item in l:
if item < minimum:
minimum = item
if item > maximum:
maximum = item
Alternatively, start with the first element and only loop over the rest; I use
[`itertools.islice()`](http://docs.python.org/2/library/itertools.html#itertools.islice)
here to avoid creating a copy of a potentially large list:
from itertools import islice
minimum = maximum = l[0]
for item in islice(l, 1, None):
if item < minimum:
minimum = item
if item > maximum:
maximum = item
or turn the list into an iterable first:
iterl = iter(l)
minimum = maximum = next(iterl)
for item in iterl:
if item < minimum:
minimum = item
if item > maximum:
maximum = item
Timing comparisons with a larger, random list:
>>> from random import shuffle
>>> l = range(1000)
>>> shuffle(l)
>>> from timeit import timeit
>>> def straight_min_max(l):
... return min(l), max(l)
...
>>> def sorted_min_max(l):
... s = sorted(l)
... return s[0], s[-1]
...
>>> def looping(l):
... l = iter(l)
... min = max = next(l)
... for i in l:
... if i < min: min = i
... if i > max: max = i
... return min, max
...
>>> timeit('f(l)', 'from __main__ import straight_min_max as f, l', number=10000)
0.5266690254211426
>>> timeit('f(l)', 'from __main__ import sorted_min_max as f, l', number=10000)
2.162343978881836
>>> timeit('f(l)', 'from __main__ import looping as f, l', number=10000)
1.1799919605255127
So even for lists of 1000 elements, the `min()` and `max()` functions are
fastest. Sorting is slowest here. The sorting version can be faster if you
allow for _in-place_ sorting, but then you'd need to generate a new random
list for each timed run as well.
Moving to a million items (and only 10 tests per timed run), we see:
>>> timeit('f(l)', 'from __main__ import straight_min_max as f, l', number=10)
1.6176080703735352
>>> timeit('f(l)', 'from __main__ import sorted_min_max as f, l', number=10)
6.310506105422974
>>> timeit('f(l)', 'from __main__ import looping as f, l', number=10)
1.7502741813659668
Last but not least, using a million items and `l.sort()` instead of
`sorted()`:
>>> def sorted_min_max(l):
... l.sort()
... return l[0], l[-1]
...
>>> l = range(1000000)
>>> shuffle(l)
>>> timeit('f(l[:])', 'from __main__ import straight_min_max as f, l', number=10)
1.8858389854431152
>>> timeit('f(l[:])', 'from __main__ import sorted_min_max as f, l', number=10)
8.408858060836792
>>> timeit('f(l[:])', 'from __main__ import looping as f, l', number=10)
2.003532886505127
Note the `l[:]`; we give each test run a copy of the list.
Conclusion: even for large lists, you are better off using the `min()` and
`max()` functions anyway. Nothing beats a good C loop. But if you have to
forgo those functions, the straight loop is the next better option.
|
Python package seems to ignore my requirements
Question: I created my first package. When I try to install it with pip in a newly
created virtualenv I get an error indicating that libs cannot be imported, yet
they are added to the `install_requires` field in `setup.py`. If I do it
outside a vierualenv, all is ok. My setup.py is here:
<https://github.com/tdi/pyPEPA/blob/dev/setup.py>
To reproduce the error:
mkvirtualenv something -p /usr/bin/python3
workon something
pip install pypepa
.
Downloading/unpacking pypepa
Running setup.py egg_info for package pypepa
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/home/tdi/.virtualenvs/koza/build/pypepa/setup.py", line 3, in <module>
import pypepa
File "./pypepa/__init__.py", line 6, in <module>
from pypepa.pepa_model import PEPAModel
File "./pypepa/pepa_model.py", line 6, in <module>
from pypepa.parsing.parser import PEPAParser
File "./pypepa/parsing/parser.py", line 5, in <module>
from pyparsing import Word, Literal, alphas, alphanums, nums, Combine, Optional, ZeroOrMore, Forward, restOfLine
ImportError: No module named 'pyparsing'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/home/tdi/.virtualenvs/koza/build/pypepa/setup.py", line 3, in <module>
import pypepa
File "./pypepa/__init__.py", line 6, in <module>
from pypepa.pepa_model import PEPAModel
File "./pypepa/pepa_model.py", line 6, in <module>
from pypepa.parsing.parser import PEPAParser
File "./pypepa/parsing/parser.py", line 5, in <module>
from pyparsing import Word, Literal, alphas, alphanums, nums, Combine, Optional, ZeroOrMore, Forward, restOfLine
ImportError: No module named 'pyparsing'
----------------------------------------
Command python setup.py egg_info failed with error code 1 in /home/tdi/.virtualenvs/koza/build/pypepa
Storing complete log in /home/tdi/.pip/pip.log
Answer: Your setup script imports pypepa which imports pypepa.pepa_model which imports
pyparsing, but pyparsing is not installed yet (we haven’t even finished
running the setup script to know what the dependencies are). The solution is
to repeat the version number in pypepa and setup.py (so you can remove the
import), or not import PEPAModel in __init__.py.
|
Accessing python container's parent object
Question: I need to create a containers that can access its children but also its
parent. Here is a simple example of how I was thinking to do that :
import numpy as np
import gc
class Node(object):
def __init__(self, name):
self.parent = None
self.child = []
self.name = name
self.mem_tracer = np.ones(10 ** 6)
def append(self, obj):
assert(isinstance(obj, Node))
self.child.append(obj)
obj.parent = self
But, with that I have a memory issue when I try to delete a Node (note that
the attribute mem_tracer is just here to be able to see if the object has been
removed from the memory or not)
This code shows the problem (the memory state at each line is given) :
print 'start' # 16.96Mb
a = Node('0') # 24.79Mb
a.append(Node('0/0')) # 32.61Mb
a.append(Node('0/1')) # 40.42Mb
a.child[0].append(Node('0/0/0')) # 48.24Mb
a.child[0].append(Node('0/0/1')) # 56.06Mb
a.child[1].append(Node('0/1/0')) # 63.87Mb
a.child[1].append(Node('0/1/1')) # 71.69Mb
del a.child[0] # 71.69Mb
gc.collect() # 48.24Mb
The garbage collector is not able to collect the deleted object as a reference
to it still exists in its children (while they are not referenced anywhere
anymore). We can see at the last line, that an explicit call to `gc.collect`
solves the problem but I would prefer to get rid of it as it is very time
consuming!
So is there an other way to access the parent container than storing it into
an attribute? Thanks in advance.
Answer: You have two choices:
* manually delete `obj.parent`
* use `weakref` to keep a pseudo-reference to the parent.
See [the docs](https://docs.python.org/3/library/weakref.html#module-weakref)
for more info on `weakref`.
|
unable to import evernote.api.client (evernte sdk)
Question: i'm trying to get started with evernote SDK , i'm using ubuntu 13.04
i installed the SDK via :
pip install evernote
but when i want to test it using :
python -c 'from evernote.api.client import EvernoteClient'
i got this :
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named api.client
What is the problem ?
EDIT : `pip install evernote` works fine i guess , it gives me this :
Requirement already satisfied (use --upgrade to upgrade): evernote in /usr/local/lib/python2.7/dist-packages/evernote-1.24.0-py2.7.egg
Requirement already satisfied (use --upgrade to upgrade): oauth2 in /usr/lib/python2.7/dist-packages (from evernote)
Requirement already satisfied (use --upgrade to upgrade): httplib2 in /usr/lib/python2.7/dist-packages (from oauth2->evernote)
Cleaning up...
here is the turorial : <http://dev.evernote.com/start/guides/python.php>
Answer: This is pretty old already, but I bet more people will hit it, so I'll put the
answer here. It seems to be a surprisingly common issue that doesn't have an
answer anywhere.
Note how the error complains about api.client but not evernote.
`Traceback (most recent call last): File "<string>", line 1, in <module>
ImportError: No module named api.client`
Most likely, the problem is that OP has a script in his path called
evernote.py, which I guess is a common name people use to name their first
evernote script. Rename the script to something less obvious and that should
do the trick.
|
Reading an array in part from a file using Python
Question: I have a file that looks like this:
C 0.210991841737 0.047663662717 0.483960886619
C -0.960965312103 0.688519555303 -0.115848688934
C 1.558206749694 0.047460114159 -0.180267436891
O -0.815251456906 -0.734986972268 -0.138532905591
H 0.223550547304 -0.045637654519 1.567373484970
H -1.759483315918 1.063259112311 0.516330435381
H -0.862256972568 1.177986074652 -1.079897880020
H 2.088617117792 -0.883541600456 0.026321487274
H 2.169362364888 0.872235726981 0.192209317060
H 1.455347299576 0.149768052462 -1.260354487995
I need to read the numbers only and store it in a 10x3 matrix. How do I do
this in python??
Answer: You could use [`pandas`](http://pandas.pydata.org/) to do this:
In [1]: import pandas as pd
In [2]: df = pd.read_csv(file_name, sep='\s+', header=None)
In [3]: df
Out[3]:
0 1 2 3
0 C 0.210992 0.047664 0.483961
1 C -0.960965 0.688520 -0.115849
2 C 1.558207 0.047460 -0.180267
3 O -0.815251 -0.734987 -0.138533
4 H 0.223551 -0.045638 1.567373
5 H -1.759483 1.063259 0.516330
6 H -0.862257 1.177986 -1.079898
7 H 2.088617 -0.883542 0.026321
8 H 2.169362 0.872236 0.192209
9 H 1.455347 0.149768 -1.260354
|
Using regex to parse kindle "My Clippings.txt" file
Question: I am currently trying to use python to parse the notes file for my kindle so
that I can keep them more organized than the chronologically ordered list that
the kindle automatically saves notes in. Unfortunately, I'm having trouble
using regex to parse the file. Here's my code so far:
import re
def parse_file(in_file):
read_file = open(in_file, 'r')
file_lines = read_file.readlines()
read_file.close()
raw_note = "".join(file_lines)
# Regex parts
title_regex = "(.+)"
title_author_regex = "(.+) \((.+)\)"
loc_norange_regex = "(.+) (Location|on Page) ([0-9]+)"
loc_range_regex = "(.+) (Location|on Page) ([0-9]+)-([0-9]+)"
date_regex = "([a-zA-Z]+), ([a-zA-Z]+) ([0-9]+), ([0-9]+)" # Date
time_regex = "([0-9]+):([0-9]+) (AM|PM)" # Time
content_regex = "(.*)"
footer_regex = "=+"
nl_re = "\r*\n"
# No author
regex_noauthor_str =\
title_regex + nl_re +\
"- Your " + loc_range_regex + " | Added on " +\
date_regex + ", " + time_regex + nl_re +\
content_regex + nl_re +\
footer_regex
regex_noauthor = re.compile(regex_noauthor_str)
print regex_noauthor.findall(raw_note)
parse_file("testnotes")
Here is the contents of "testnotes":
Title
- Your Highlight Location 3360-3362 | Added on Wednesday, March 21, 2012, 12:16 AM
Note content goes here
==========
What I want:
[('Title', 'Highlight', 'Location', '3360', '3362', 'Wednesday', 'March', '21', '2012', '12', '16', 'AM',
But when I run the program, I get:
[('Title', 'Highlight', 'Location', '3360', '3362', '', '', '', '', '', '', '', '')]
I'm fairly new to regex, but I feel like this should be fairly
straightforward.
Answer: You need to escape the `|` in `"- Your " + loc_range_regex + " | Added on " +\`
to: `"- Your " + loc_range_regex + " \| Added on " +\`
`|` is the OR operator in a regex.
|
Looking for OOP Pythonic approach for putting objects in a 'list object' as opposed to just using [list]
Question: For some reason I cannot conceptualize how to use Checkbook.class object
instead of "ledger [list]" Trying to keep my approach OOP. What is a best
practices approach to the objectives of this code? (Yes, I have other "newbie"
questions too, but I would be happy just to get some input on this.)
import sys
import time
transNum=0
ledger = []
debitInput=['Check Number: ', 'Transaction Date: ',
'Payee: ', 'Amount: ', 'Memo (or Enter to skip): ']
creditInput=['Check Number: ', 'Transaction Date: ',
'Source: ', 'Amount: ', 'Memo (or Enter to skip): ']
# a Payee is a persistent record/lookup of current, past and new payees
class Payee:
pass
# a Source is a persistent record/lookup of current, past and new sources
class Source:
pass
# a Checkbook is a collection of Transaction objects upon which queries may be performed
class Checkbook:
def __init__(self, newTrans):
pass
# a Transaction is a collection of Debit and Credit objects
class Transaction:
def __init__(self, chkNum, transDate, thirdParty, amount, memo=''):
self.chkNum = chkNum
self.transDate = transDate
self.memo=memo
self.thirdParty=thirdParty
self.amount=amount
self.transNum = transNum
class Debit(Transaction):
def __init__(self, *args):
Transaction.__init__(self, *args)
self.payee=self.thirdParty
del self.thirdParty
self.amount=int(self.amount)*-1
class Credit(Transaction):
def __init__(self, *args):
Transaction.__init__(self, *args)
self.source=self.thirdParty
del self.thirdParty
self.amount=int(self.amount)
while True:
transact = []
transNum += 1
choice=input('Posting debit [d], credit [c] or [x] to exit: ')
if choice == 'x': break
elif choice == 'd':
for field in debitInput:
field = input(field)
transact.append(field)
trans = Debit(transact[0], transact[1], transact[2], transact[3], transact[4])
ledger.append(trans)
elif choice == 'c':
for field in creditInput:
field = input(field)
transact.append(field)
trans = Credit(transact[0], transact[1], transact[2], transact[3], transact[4])
Answer:
class Checkbook:
def __init__(self):
self.transactions = [] # Checkbook is just a wrapper around a list
def __getitem__(self, index): # implementing [x]
return self.transactions[index]
def __setitem__(self, index, transaction): #implementing [x] = i
self.transactions[index] = transaction
def append(self, transaction): # implementing .append(x)
self.transactions.append(transaction)
def extend(self, transaction_list): # implementing .extend([x,y,z])
self.transactions.extend(transaction_list)
# and so on for every method which you want to support
Or you can [subclass `list`](http://stackoverflow.com/questions/8180014/how-
to-subclass-python-list-without-type-problems).
Is this for homework? It's silly to assign this in Python. [You'd never really
want to subclass `list`](http://stackoverflow.com/questions/8180014/how-to-
subclass-python-list-without-type-problems#comment10047774_8180014). I had a
better exercise in university in which I had to re-implement a `std::vector`
using templates, a dynamic array (with `malloc()`), and operator
overloading... what fun! The `std::map` exercise was even better :)
|
How to convert dictionary values into list in Python / Django?
Question: In my Django template, I call this frequently:
{% for name, address in directory.addressbook.items %}
{% for street in address.list %}
{{street.number}}
How do I create this as a filter? I've tried this, but it doesn't work.
In the template, I call:
{{directory.addressbook.items|all_numbers}}
And in my filter definition I have:
def all_numbers(data):
number_list=[]
if isinstance(data, dict):
for name, address in data:
for street in data.list():
number_list.append(street)
return number_list
But all I get returned is "[ ]". What am I doing wrong?
Answer: You need to register your function as a template filter. Also, this code will
need to be in a module and then imported into your template as such...
# custom_filters.py
from django import template
register = template.Library()
@register.filter
def all_numbers(data):
number_list=[]
if isinstance(data, dict):
for name, address in data:
for street in data.list(): # this will raise an exception
number_list.append(street)
return number_list
# your-template.html
{% load custom_filters %}
{{ directory.addressbook.items|all_numbers }}
|
python-sip: How to access a DLL from both Python and C++
Question: I have a C++ GUI, it load a DLL when running. I use SIP to import the DLL in
python. I need to embed the python part in the GUI, and some data are needed
to exchange between python and C++.
For example, in the C++ GUI, I can enter command from a panel, such as
"drawSomething()", it will call corresponding function in python, and the
result will be shown in the GUI.
Can I use SIP to extract a C++ object from python object (just like the way
boost.python does), or is there a better way to share data between python and
c++ seamlessly?
thanks.
Answer: It turns out that I do not need to do anything complicated... In my case,
there is no difference to call functions in DLL from C++ or from python code
embedded in C++. I am totally over-thinked.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.