title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python noobie scoping question
6,171,033
5
2011-05-29T23:11:49Z
6,171,122
7
2011-05-29T23:32:05Z
[ "python", "scoping" ]
I wrote this code: ``` x = 0 def counter(): x = 1 def temp(self): print x x += 1 return temp ``` Trying to test if python is lexical or dynamic scope. My thinking was that ``` y = counter() y() ``` Should either print 0 or 1, and that would tell me how python is scoped. However, calling y throws an exception...
From [the docs](http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces): > A special quirk of Python is that – if > no global statement is in effect – > assignments to names always go into > the innermost scope. Assignments do > not copy data — they just bind names > to objects. So, when Pyth...
Building Python and more on missing modules
6,171,210
23
2011-05-29T23:50:31Z
6,171,511
32
2011-05-30T01:17:11Z
[ "python", "ubuntu" ]
I have another thread asking help on "missing zlib". With the nice help the problem has been resolved (almost). Now I am interested in building Python myself (on Ubuntu 10.10). A few important questions have caught my attention: 1. After building Python (say 2.7.1), do I need to rebuild Python if I have missing modu...
Here is how to build Python and fix any dependencies. I am assuming that you want this Python to be entirely separate from the Ubuntu release Python, so I am specifying the --prefix option to install it all in /home/python27 using the standard Python layout, i.e. site-packages instead of dist-packages. ``` 1. Get the ...
How to set the button sticky property properly?
6,171,493
9
2011-05-30T01:12:41Z
6,176,498
7
2011-05-30T12:49:28Z
[ "python", "tkinter", "sticky" ]
I've been playing around with tkinter a bit and I can't figure out why the "sticky" attribute doesn't seem to be working with my button. I've specified sticky to be NW which should cause my button to stick to the top left edge but for some reason it sticks to the top right. Any idea why? ``` from tkinter import * from...
The sticky attribute applies to the cell that the widget is in, rather than to the whole grid or whole window. So, the widget *is* anchored to the nw corner of its cell, it's just that you can't tell because the cell is exactly the same width as the button. Since you are placing the button in the upper right cell (row...
How do I read album artwork using python?
6,171,565
3
2011-05-30T01:32:54Z
6,173,176
12
2011-05-30T06:55:49Z
[ "python", "object", "mp3", "music", "id3" ]
In my searches I have found that there are a few libraries that might be able to do this by reading ID3 tags. If so - which one would be the best to use? I don't plan on writing any data just reading. Also I'm trying to make this app as portable as possible so the least amount of dependencies would be a huge bonus. W...
I'd recommend [mutagen](http://code.google.com/p/mutagen/), it's a pure python library with no other dependencies and it supports a lot of different audio metadata formats/tags (MP3, FLAC, M4A, Monkey's Audio, Musepack, and more). To extract artwork from an ID3 v2.4 MP3 saved with iTunes: ``` from mutagen import File ...
How do I add PIL to PyDev in Eclipse, so i could import it and use it in my project?
6,171,749
13
2011-05-30T02:20:22Z
6,486,750
8
2011-06-26T21:06:12Z
[ "python", "django", "eclipse", "python-imaging-library", "pydev" ]
I am trying to work with PIL in my project but the pydev can't seem to find it in my project. First of all I can see it when I enter the python shell, I can import it and I see it in the python sys.path. Second, I Added it to the PYTHONPATH in eclipse. I restarted eclipse, but still, when I try to do "from PIL import ...
Had the same problem here. Got it resolved by adding `/usr/share/pyshared` to the Libraries tab in window->preferences->pydev->Interpreter - Python. There were a lot of `/usr/lib/python*` paths with the compiled libraries (the C stuff with python bindings) where included already, but not `/usr/share`... parts with the...
How do I add PIL to PyDev in Eclipse, so i could import it and use it in my project?
6,171,749
13
2011-05-30T02:20:22Z
6,849,785
10
2011-07-27T19:03:20Z
[ "python", "django", "eclipse", "python-imaging-library", "pydev" ]
I am trying to work with PIL in my project but the pydev can't seem to find it in my project. First of all I can see it when I enter the python shell, I can import it and I see it in the python sys.path. Second, I Added it to the PYTHONPATH in eclipse. I restarted eclipse, but still, when I try to do "from PIL import ...
Try to go to `Window -> Preferences -> Pydev-> Interpreter -> Python Interpreter -> Forced Builtins` tab. Then add a `PIL` entry and apply. I've had the same `unresolved import` error when tried to import from this particular package (other packages worked fine), and found [this information](http://pydev.org/manual_101...
What is an easy way to clean an unparsable csv file
6,172,123
2
2011-05-30T03:54:26Z
6,172,230
8
2011-05-30T04:15:46Z
[ "php", "python", "mysql", "csv" ]
The csv file was created correctly but the name and address fields contain every piece of punctuation there is available. So when you try to import into mysql you get parsing errors. For example the name field could look like this, "john ""," doe". I have no control over the data I receive so I'm unable to stop people ...
This may not be a usable answer but someone needs to say it. **You shouldn't have to do this**. CSV is a file format with an expected data encoding. If someone is supplying you a CSV file then it should be delimited and escaped properly, otherwise its a corrupted file and you should reject it. Make the supplier re-expo...
Static root page on Google AppEngine
6,172,585
2
2011-05-30T05:29:46Z
6,172,653
9
2011-05-30T05:42:23Z
[ "python", "google-app-engine" ]
I'm trying to set up a static landing page for a google appengine application. However I get 404 when I go to the root of the site. It works fine locally just doesn't work when I deploy it. The app.html page work so its just the landing page thats not working. Here's something from app.yaml ``` handlers: - url: /rest...
Change those backslashes to forward-slashes. Should be: ``` - url: / static_files: static/index.html upload: static/index.html ``` [Backslashes are escape characters](http://docs.python.org/reference/lexical_analysis.html#string-literals). So you were specifying a path that doesn't exist.
Find the Friday of previous/last week in python
6,172,782
12
2011-05-30T06:02:41Z
6,172,810
34
2011-05-30T06:07:40Z
[ "python", "datetime" ]
Eg1. Suppose I have a day 4/30/07 .Then I need to get 4/27/07. Eg2. Suppose I have a day 6/29/07 .Then I need to get 6/22/07.
Assuming `day` is a `datetime.date` or `datetime.datetime` object, this code creates a `datetime`/`date` object for last week's friday: ``` friday = day - timedelta(days=day.weekday()) + timedelta(days=4, weeks=-1) ``` Explanation: `timedelta(days=day.weekday())` is the offset between monday and `day` so adding 4 day...
Find the Friday of previous/last week in python
6,172,782
12
2011-05-30T06:02:41Z
31,301,921
10
2015-07-08T19:27:17Z
[ "python", "datetime" ]
Eg1. Suppose I have a day 4/30/07 .Then I need to get 4/27/07. Eg2. Suppose I have a day 6/29/07 .Then I need to get 6/22/07.
An another and easier way is to use [python-dateutil](http://labix.org/python-dateutil). To get the previous Friday : ``` >>> from dateutil.relativedelta import relativedelta, FR >>> from datetime import datetime >>> datetime(2015, 7, 8) + relativedelta(weekday=FR(-1)) datetime.datetime(2015, 7, 3, 0, 0) ``` And the ...
Parsing php array in python
6,174,031
2
2011-05-30T08:37:22Z
6,174,071
10
2011-05-30T08:42:03Z
[ "php", "python", "parsing" ]
I'm getting a PHP array from a web page (as a string). It looks like : ``` Array ( [k1] => Array ( [a] => Array ( [id] => 1 [age] => 60 ) [b] => Array ( [id] => 2 [age] => 30 ) ) [...
That's not JSON, that's just how PHP prints arrays. If you want to create JSON of the array, check out [json\_encode](http://php.net/manual/en/function.json-encode.php) for PHP. Then use [Python's JSON library](http://docs.python.org/library/json.html) (or here for [py3](http://docs.python.org/py3k/library/json.html?hi...
Generate in flight string from [A-z]
6,174,827
6
2011-05-30T09:58:44Z
6,174,845
8
2011-05-30T09:59:58Z
[ "python", "random" ]
I want to know what is a simplest way to write method which generates me number from 1 to 50, and then depends of generated number returns me string like: `Abcdef` if generated number is 6 `Abcdefghi` if generated number is 9. I'm using python 3.2
There's a few approaches, the simplest: ``` >>> import string >>> import random >>> string.ascii_letters[:random.randint(1, 50)].title() 'Abcdefghijklmnopq' >>> string.ascii_letters[:random.randint(1, 50)].title() 'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq' >>> string.ascii_letters[:random.randint(1, 50)].title() 'A...
pyserial enumerate ports
6,176,485
5
2011-05-30T12:47:42Z
11,271,506
12
2012-06-30T04:50:48Z
[ "python", "pyserial" ]
I need list or enumerate of existing serial ports, Till now I was using this method **enumerate\_serial\_ports()**, but its not working with windows 7. Do you know some alternative how can I find out available serial ports under windows 7? ``` def enumerate_serial_ports(): """ Uses the Win32 registry to return an ...
There's now a [list\_ports](http://pyserial.sourceforge.net/pyserial_api.html#module-serial.tools.list_ports) module built in to pyserial. ``` In [26]: from serial.tools import list_ports In [27]: list_ports.comports() Out[27]: [('/dev/ttyS3', 'ttyS3', 'n/a'), ('/dev/ttyS2', 'ttyS2', 'n/a'), ('/dev/ttyS1', 'ttyS1',...
Why does PIL thumbnail not resizing correctly?
6,177,532
5
2011-05-30T14:29:11Z
6,177,769
11
2011-05-30T14:52:05Z
[ "python", "django", "django-models", "python-imaging-library" ]
I am trying to create and save a thumbnail image when saving the original user image in the `userProfile` model in my project, below is my code: ``` def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) THUMB_SIZE = 45, 45 image = Image.open(join(MEDIA_ROOT, self.headshot.name)) ...
The [*image.thumbnail()*](http://www.pythonware.com/library/pil/handbook/image.htm#Image.thumbnail) function will maintain the aspect ratio of the original image. Use [*image.resize()*](http://www.pythonware.com/library/pil/handbook/image.htm#Image.resize) instead. **UPDATE** ``` image = image.resize(THUMB_SIZE, Ima...
Django Ajax "FORBIDDEN" error
6,178,048
14
2011-05-30T15:18:52Z
6,178,326
9
2011-05-30T15:49:47Z
[ "python", "ajax", "django", "json" ]
I've seen instances where people are getting forbidden errors while attempting to make remote Ajax requests, but I'm making a local request and I also have CSRF turned on in my middleware. errorThrown is returning "Forbidden" I think the issue might be that I'm trying to send this to a normal view (the current page)....
You will get 403 errors if you have csrf on, try adding in `views.py` to see if this is causing it: ``` from django.views.decorators.csrf import csrf_exempt @csrf_exempt view class/method ```
Django Ajax "FORBIDDEN" error
6,178,048
14
2011-05-30T15:18:52Z
6,178,607
18
2011-05-30T16:23:33Z
[ "python", "ajax", "django", "json" ]
I've seen instances where people are getting forbidden errors while attempting to make remote Ajax requests, but I'm making a local request and I also have CSRF turned on in my middleware. errorThrown is returning "Forbidden" I think the issue might be that I'm trying to send this to a normal view (the current page)....
You need a CSRF token even if the request is to the same domain. There's code here to add a CSRF token to your AJAX requests (with jQuery): <https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax> This link points to version 1.7, if you are using a different version of Django you can select your version from th...
Open a text file using notepad as a help file in python?
6,178,154
6
2011-05-30T15:29:40Z
6,178,200
21
2011-05-30T15:35:08Z
[ "python" ]
I would like to give users of my simple program the opportunity to open a help file to instruct them on how to fully utilize my program. Ideally i would like to have a little blue help link on my GUI that could be clicked at any time resulting in a .txt file being opened in a native text editor, notepad for example. I...
``` import webbrowser webbrowser.open("file.txt") ``` Despite it's name it will open in Notepad, gedit and so on. Never tried it but it's said it works. An alternative is to use ``` osCommandString = "notepad.exe file.txt" os.system(osCommandString) ``` or as subprocess: ``` import subprocess as sp programName = "...
easy_install fails on error "Couldn't find setup script" after binary upload?
6,178,664
8
2011-05-30T16:29:24Z
6,238,019
7
2011-06-04T16:42:54Z
[ "python", "binary", "easy-install", "python-c-extension" ]
After uploading a binary distribution of my Python C extension with `python setup.py bdist upload`, `easy_install [my-package-name]` fails on "error: Couldn't find a setup script in /tmp/easy\_install/package-name-etc-etc". What am I doing wrong?
easy\_install expects to find either a source distribution, or an egg. It's best to upload source distributions (`sdist`) to PyPI (or whatever distribution server you are using), and only upload eggs if your python package contains C extensions, and then only for Windows eggs (see my answer to [Can I create a single eg...
easy_install fails on error "Couldn't find setup script" after binary upload?
6,178,664
8
2011-05-30T16:29:24Z
14,675,245
29
2013-02-03T17:38:07Z
[ "python", "binary", "easy-install", "python-c-extension" ]
After uploading a binary distribution of my Python C extension with `python setup.py bdist upload`, `easy_install [my-package-name]` fails on "error: Couldn't find a setup script in /tmp/easy\_install/package-name-etc-etc". What am I doing wrong?
This may not be related to your specific problem, but I am providing this information in case it is helpful to others. I hit exactly this error when running 'easy\_install xyz'. The problem turned out to be that I had a subdirectory named 'xyz' in the current working directory and easy\_install was expecting to find a...
Python: How to count the number of objects created?
6,179,182
3
2011-05-30T17:32:51Z
6,179,214
13
2011-05-30T17:37:14Z
[ "python", "object", "static", "count" ]
I'm new to Python. My question is, what is the best way to count the number of python objects for keeping track of number of objects exist at any given time? I thought of using a static variable. I have read several Q & A on static variables of Python, but I could not figure out how I could achieve object counting usi...
Use `self.__class__.iMenuNumber` or `baseMENUS.iMenuNumber` instead of `self.iMenuNumber` to set the var on the class instead of the instance. Additionally, Hungarian Notation is not pythonic (actually, it sucks in all languages) - you might want to stop using it. See <http://www.python.org/dev/peps/pep-0008/> for som...
How to install a Swig enabled Python extension (QuickFix)
6,179,527
3
2011-05-30T18:18:19Z
6,181,091
7
2011-05-30T22:01:25Z
[ "python", "windows", "installation", "quickfix" ]
[QuickFix](http://www.quickfixengine.org/) includes bindings for Python. How do I install QuickFix so that I can `import quickfix` in Python on Windows? * `easy_install quickfix` doesn't work * both binary and source [downloads](http://www.quickfixengine.org/download.html) don't include `setup.py` * The source downloa...
<http://www.lfd.uci.edu/~gohlke/pythonlibs/#quickfix>
Python wait x secs for a key and continue execution if not pressed
6,179,537
5
2011-05-30T18:20:25Z
6,179,750
14
2011-05-30T18:47:51Z
[ "python", "wait" ]
I'm a n00b to python, and I'm looking a code snippet/sample which performs the following: * Display a message like "Press any key to configure or wait X seconds to continue" * Wait, for example, 5 seconds and continue execution, or enter a configure() subroutine if a key is pressed. Thank you for your help! Yvan Jan...
If you're on Unix/Linux then the [select](http://docs.python.org/library/select.html) module will help you. ``` import sys from select import select print "Press any key to configure or wait 5 seconds..." timeout = 5 rlist, wlist, xlist = select([sys.stdin], [], [], timeout) if rlist: print "Config selected..." ...
What am I not doing right in this django file upload form?
6,179,925
12
2011-05-30T19:10:05Z
6,180,019
24
2011-05-30T19:23:03Z
[ "python", "django", "validation" ]
This is my form: ``` from django import forms class UploadFileForm(forms.Form): titl = forms.CharField(max_length=50) ffile = forms.FileField() ``` This is my views.py file: ``` def handle_uploaded_file(file_path): print "handle_uploaded_file" dest = open(file_path.name,"wb") for chunk in f...
``` form = UploadFileForm(request.POST, request.FILES) ```
What am I not doing right in this django file upload form?
6,179,925
12
2011-05-30T19:10:05Z
15,738,293
33
2013-04-01T05:48:40Z
[ "python", "django", "validation" ]
This is my form: ``` from django import forms class UploadFileForm(forms.Form): titl = forms.CharField(max_length=50) ffile = forms.FileField() ``` This is my views.py file: ``` def handle_uploaded_file(file_path): print "handle_uploaded_file" dest = open(file_path.name,"wb") for chunk in f...
Just for future reference. I had the same error, though I included `request.FILES` in form initialization. The problem was in the template: I forgot to add `enctype="multipart/form-data"` attribute to the `<form>` tag.
python list of dictionaries
6,179,939
8
2011-05-30T19:13:31Z
16,107,398
9
2013-04-19T14:49:54Z
[ "python", "list", "dictionary" ]
I have a simple code to fetch users from db using sqlalchemy and return them as json. My problem is how to format the output to get something like this: ``` {"results": [{"id":1, "username":"john"},{"id":2,"username":"doe"}]} ``` my code outputs an error which I cant seem to fix being a newbie in python: ``` d = [] ...
I solved this error by simply saying ``` return jsonify( results = d ) ``` instead of ``` return jsonify( d ) ```
Custom Python Exceptions with Error Codes and Error Messages
6,180,185
22
2011-05-30T19:41:59Z
6,180,231
37
2011-05-30T19:47:59Z
[ "python", "error-handling", "custom-exceptions" ]
``` class AppError(Exception): pass class MissingInputError(AppError): pass class ValidationError(AppError): pass ``` ... ``` def validate(self): """ Validate Input and save it """ params = self.__params if 'key' in params: self.__validateKey(escape(params['key'][0])) else: ...
Here's a quick example to writing a custom `Exception` class with special codes... ``` class ErrorWithCode(Exception): def __init__(self, code): self.code = code def __str__(self): return repr(self.code) try: raise ErrorWithCode(1000) except ErrorWithCode as e: print "Received error wi...
Emacs for Python programming: module/class outline/browser
6,180,272
14
2011-05-30T19:52:49Z
6,192,461
8
2011-05-31T19:20:01Z
[ "python", "emacs", "navigation" ]
I am currently using <https://github.com/fgallina/python.el> + ropemacs, but I am missing module browser: separate buffer that outlines names defined in the current module (list of classes with their methods). Google says that there are OO-browser and emacs-code-browser, but they looks outdated and I can't find any men...
I think [ECB](http://ecb.sourceforge.net/) (Emacs Code Browser) is worth a try. I don't use it all the time but it can be very handy. Especially useful is the "ECB Methods" window which displays an outline of all members of a module. Here is a screenshot with the ECB Methods window in the lower left corner: <http://de...
Is there a python IDE that will tell you the type of a variable when you hover over it?
6,180,349
3
2011-05-30T20:04:52Z
6,180,432
8
2011-05-30T20:16:40Z
[ "python", "eclipse", "vim", "emacs", "ide" ]
Sometimes I write projects and don't return to them until months later. Unfortunately for me I forget what was intended to be passed into a function. I would like to be able to hover over an argument and see the type such as integer, string, some class, etc. Is there an IDE out there that will do this for me? Any help ...
There is no way to infer the type normally, so no IDE will be able to do this. Why not just use docstrings? ``` def foo(a, b): """ Take your arguments back, I don't want them! a -- int b -- str """ return a, b ``` In Python 3 you could also take advantage of function annotations: ``` def fo...
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data
6,180,521
44
2011-05-30T20:28:58Z
6,190,499
69
2011-05-31T16:16:24Z
[ "python", "unicode", "python-2.x" ]
how does the unicode thing works on python2? i just dont get it. here i download data from a server and parse it for JSON. ``` Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/eventlet-0.9.12-py2.6.egg/eventlet/hubs/poll.py", line 92, in wait readers.get(fileno, noop).cb(fileno) ...
The string you're trying to parse as a JSON is not encoded in UTF-8. Most likely it is encoded in ISO-8859-1. Try the following: ``` json.loads(unicode(opener.open(...), "ISO-8859-1")) ``` That will handle any umlauts that might get in the JSON message. You should read Joel Spolsky's [The Absolute Minimum Every Soft...
How to fix socket.gaierror: (11004, 'getaddrinfo failed') error in GAE?
6,180,720
5
2011-05-30T21:02:53Z
9,603,874
7
2012-03-07T15:03:56Z
[ "python", "google-app-engine", "sockets", "aptana" ]
I'm using Aptana and GAE. When I run GAE launcher or run a server in Aptana 3, I get this error... I've downloaded the lastest version of GAE and still doesnt work... ``` Traceback (most recent call last): File "C:\google_appengine\dev_appserver.py", line 76, in <module> run_file(__file__, globals()) File "C:\...
FIXED! after days looking for this problem: I just deleted this line "0.0.0.0 localhost " from my hosts file located in "C:\Windows\System32\drivers\etc" thanks anyway!!
Are there any way to scramble strings in python?
6,181,304
5
2011-05-30T22:39:00Z
6,181,343
16
2011-05-30T22:45:03Z
[ "python", "string", "list", "scramble" ]
I'm writing a code and I need to scramble the letters of strings from a list in python. For instance I have a list of strings like: ``` l = ['foo', 'biology', 'sequence'] ``` and I want something like this: ``` l = ['ofo', 'lbyooil', 'qceaenes'] ``` which is the best way to do it? Very thanks for your help!
Python has batteries included.. ``` >>> from random import shuffle >>> def shuffle_word(word): ... word = list(word) ... shuffle(word) ... return ''.join(word) ``` A list comprehension is an easy way to create a new list: ``` >>> L = ['foo', 'biology', 'sequence'] >>> [shuffle_word(word) for word in L] ['o...
pass a unit test if an exception isn't thrown
6,181,555
12
2011-05-30T23:23:01Z
6,181,656
11
2011-05-30T23:45:05Z
[ "python", "unit-testing" ]
In the python unittest framework, is there a way to pass a unit test if an exception wasn't thrown and fail with an AssertRaise otherwise?
If I understand your question correctly, you *could* do something like this: ``` def test_does_not_raise_on_valid_input(self): raised = False try: do_something(42) except: raised = True self.assertFalse(raised, 'Exception raised') ``` ...assuming that you have a corresponding test that...
Converting a String to a List of Words?
6,181,763
23
2011-05-31T00:09:24Z
6,181,784
32
2011-05-31T00:13:53Z
[ "python", "string", "list", "words", "text-segmentation" ]
I'm trying to convert a string to a list of words using python. I want to take something like the following: ``` string = 'This is a string, with words!' ``` Then convert to something like this : ``` list = ['This', 'is', 'a', 'string', 'with', 'words'] ``` Notice the omission of punctuation and spaces. What would ...
Try this: ``` import re mystr = 'This is a string, with words!' wordList = re.sub("[^\w]", " ", mystr).split() ``` **How it works :** From the docs : ``` re.sub(pattern, repl, string, count=0, flags=0) ``` Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by th...
Converting a String to a List of Words?
6,181,763
23
2011-05-31T00:09:24Z
6,181,792
17
2011-05-31T00:15:21Z
[ "python", "string", "list", "words", "text-segmentation" ]
I'm trying to convert a string to a list of words using python. I want to take something like the following: ``` string = 'This is a string, with words!' ``` Then convert to something like this : ``` list = ['This', 'is', 'a', 'string', 'with', 'words'] ``` Notice the omission of punctuation and spaces. What would ...
To do this properly is quite complex. For your research, it is known as word tokenization. You should look at [NLTK](http://nltk.org) if you want to see what others have done, rather than starting from scratch: ``` >>> import nltk >>> paragraph = u"Hi, this is my first sentence. And this is my second." >>> sentences =...
Converting a String to a List of Words?
6,181,763
23
2011-05-31T00:09:24Z
13,734,966
22
2012-12-06T00:22:28Z
[ "python", "string", "list", "words", "text-segmentation" ]
I'm trying to convert a string to a list of words using python. I want to take something like the following: ``` string = 'This is a string, with words!' ``` Then convert to something like this : ``` list = ['This', 'is', 'a', 'string', 'with', 'words'] ``` Notice the omission of punctuation and spaces. What would ...
I think this is the simplest way for anyone else stumbling on this post given the late response: ``` >>> string = 'This is a string, with words!' >>> string.split() ['This', 'is', 'a', 'string,', 'with', 'words!'] ```
How do you create different variable names while in a loop? (Python)
6,181,935
32
2011-05-31T00:53:48Z
6,181,959
12
2011-05-31T00:58:38Z
[ "python" ]
For example purposes... ``` for x in range(0,9): string'x' = "Hello" ``` So I end up with string1, string2, string3... all equaling "Hello"
It is really bad idea, but... ``` for x in range(0, 9): globals()['string%s' % x] = 'Hello' ``` and then for example: ``` print(string3) ``` will give you: ``` Hello ``` --- However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to ...
How do you create different variable names while in a loop? (Python)
6,181,935
32
2011-05-31T00:53:48Z
6,181,978
44
2011-05-31T01:02:19Z
[ "python" ]
For example purposes... ``` for x in range(0,9): string'x' = "Hello" ``` So I end up with string1, string2, string3... all equaling "Hello"
Sure you can; its called a [dictionary](http://docs.python.org/tutorial/datastructures.html#dictionaries): ``` d={} for x in range(1,10): d["string{0}".format(x)]="Hello" In [7]: d["string5"] Out[7]: 'Hello' In [8]: d Out[8]: {'string1': 'Hello', 'string2': 'Hello', 'string3': 'Hello', 'string4': 'Hello'...
Python -- Send Email When Exception Is Raised?
6,182,693
10
2011-05-31T03:20:22Z
6,187,851
38
2011-05-31T12:52:30Z
[ "python", "exception-handling" ]
I have a `python` class with many methods(): `Method1()` `Method2()` ........... ........... `MethodN()` All methods -- while performing different tasks -- have the same scheme: ``` do something do something else has anything gone wrong? raise an exception ``` --- I want to be able to get an email whenever...
like @User said before Python has [`logging.handlers.SMTPHandler`](https://docs.python.org/3.5/library/logging.handlers.html#logging.handlers.SMTPHandler) to send logged error message. Use logging module! Overriding exception class to send an email is a bad idea. Quick example: ``` import logging import logging.handl...
Why is parenthesis in print voluntary in Python 2.7?
6,182,964
60
2011-05-31T04:18:27Z
6,183,002
70
2011-05-31T04:25:02Z
[ "python", "printing", "python-3.x", "python-2.7" ]
In Python 2.7 both the following will do the same ``` print("Hello, world!") # Prints "Hello, world!" print "Hello, world!" # Prints "Hello, world!" ``` However the following will not ``` print("Hello,", "world!") # Prints the tuple: ("Hello,", "world!") print "Hello,", "world!" # Prints the words "Hello, world!" ...
In Python 2.x `print` is actually a special statement and not a function\*. This is also why it can't be used like: `lambda x: print x` Note that `(expr)` does not create a Tuple (it results in `expr`), but `,` does. This likely results in the confusion between `print (x)` and `print (x, y)` in Python 2.7 ``` (1) ...
Why is parenthesis in print voluntary in Python 2.7?
6,182,964
60
2011-05-31T04:18:27Z
11,973,768
7
2012-08-15T17:05:50Z
[ "python", "printing", "python-3.x", "python-2.7" ]
In Python 2.7 both the following will do the same ``` print("Hello, world!") # Prints "Hello, world!" print "Hello, world!" # Prints "Hello, world!" ``` However the following will not ``` print("Hello,", "world!") # Prints the tuple: ("Hello,", "world!") print "Hello,", "world!" # Prints the words "Hello, world!" ...
Here we have interesting side effect when it comes to utf-8. ``` >> greek = dict( dog="σκύλος", cat="γάτα" ) >> print greek['dog'], greek['cat'] σκύλος γάτα >> print (greek['dog'], greek['cat']) ('\xcf\x83\xce\xba\xcf\x8d\xce\xbb\xce\xbf\xcf\x82', '\xce\xb3\xce\xac\xcf\x84\xce\xb1') ``` The last p...
PHP passing a class as a reference?
6,182,993
2
2011-05-31T04:23:48Z
6,183,007
7
2011-05-31T04:25:38Z
[ "php", "python" ]
in Python, you could do something like this: ``` class SomeClass(object): pass s = SomeClass someClassInstance = s() ``` How could you accomplish the same effect in PHP? From what I understand, you cannot do this? Is this true?
You can create instances of dynamic class names; simply pass the name of the class as a string: ``` class SomeClass {} $s = 'SomeClass'; $someClassInstance = new $s(); ```
How do I run Selenium in Xvfb?
6,183,276
55
2011-05-31T05:18:33Z
6,183,321
24
2011-05-31T05:23:41Z
[ "python", "linux", "user-interface", "unix", "selenium" ]
I'm on EC2 instance. So there is no GUI. ``` $pip install selenium $sudo apt-get install firefox xvfb ``` Then I do this: ``` $Xvfb :1 -screen 0 1024x768x24 2>&1 >/dev/null & $DISPLAY=:1 java -jar selenium-server-standalone-2.0b3.jar 05:08:31.227 INFO - Java: Sun Microsystems Inc. 19.0-b09 05:08:31.229 INFO - OS: L...
open a terminal and run this command `xhost +`. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands Also make sure in your /etc/environment file there is a line ``` export DISPLAY=:0.0 ``` And then, run your tests to see if your issu...
How do I run Selenium in Xvfb?
6,183,276
55
2011-05-31T05:18:33Z
6,183,775
16
2011-05-31T06:27:55Z
[ "python", "linux", "user-interface", "unix", "selenium" ]
I'm on EC2 instance. So there is no GUI. ``` $pip install selenium $sudo apt-get install firefox xvfb ``` Then I do this: ``` $Xvfb :1 -screen 0 1024x768x24 2>&1 >/dev/null & $DISPLAY=:1 java -jar selenium-server-standalone-2.0b3.jar 05:08:31.227 INFO - Java: Sun Microsystems Inc. 19.0-b09 05:08:31.229 INFO - OS: L...
This is the setup I use: Before running the tests, execute: ``` export DISPLAY=:99 /etc/init.d/xvfb start ``` And after the tests: ``` /etc/init.d/xvfb stop ``` The `init.d` file I use looks like this: ``` #!/bin/bash XVFB=/usr/bin/Xvfb XVFBARGS="$DISPLAY -ac -screen 0 1024x768x16" PIDFILE=${HOME}/xvfb_${DISPLAY...
How do I run Selenium in Xvfb?
6,183,276
55
2011-05-31T05:18:33Z
6,300,672
127
2011-06-10T00:10:38Z
[ "python", "linux", "user-interface", "unix", "selenium" ]
I'm on EC2 instance. So there is no GUI. ``` $pip install selenium $sudo apt-get install firefox xvfb ``` Then I do this: ``` $Xvfb :1 -screen 0 1024x768x24 2>&1 >/dev/null & $DISPLAY=:1 java -jar selenium-server-standalone-2.0b3.jar 05:08:31.227 INFO - Java: Sun Microsystems Inc. 19.0-b09 05:08:31.229 INFO - OS: L...
You can use [PyVirtualDisplay](http://pypi.python.org/pypi/PyVirtualDisplay) (a Python wrapper for Xvfb) to run headless WebDriver tests. ``` #!/usr/bin/env python from pyvirtualdisplay import Display from selenium import webdriver display = Display(visible=0, size=(800, 600)) display.start() # now Firefox will run...
How do I run Selenium in Xvfb?
6,183,276
55
2011-05-31T05:18:33Z
11,383,637
36
2012-07-08T13:52:03Z
[ "python", "linux", "user-interface", "unix", "selenium" ]
I'm on EC2 instance. So there is no GUI. ``` $pip install selenium $sudo apt-get install firefox xvfb ``` Then I do this: ``` $Xvfb :1 -screen 0 1024x768x24 2>&1 >/dev/null & $DISPLAY=:1 java -jar selenium-server-standalone-2.0b3.jar 05:08:31.227 INFO - Java: Sun Microsystems Inc. 19.0-b09 05:08:31.229 INFO - OS: L...
The easiest way is probably to use xvfb-run: ``` DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar ``` xvfb-run does the whole X authority dance for you, give it a try!
Compile Syntax Error: non ASCII letters in a string
6,183,311
8
2011-05-31T05:22:30Z
6,184,011
8
2011-05-31T06:58:41Z
[ "python", "unicode", "compiler-errors", "ascii" ]
I have a python file that contains a long string of HTML. When I compile & run this file/script I get this error: ``` _SyntaxError: Non-ASCII character '\x92' in file C:\Users...\GlobalVars.py on line 2509, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details_ ``` I have followed the...
First, in order to prevent problems like the one specified in the question you should not *ever* use other encoding than `utf-8` for python source code. This is the correct header to use ``` #! /usr/bin/env python # -*- coding: utf-8 -*- ``` Now you have to convert the file from whatever encoding you may have to `ut...
How to initialize classes (not instances) in Python?
6,183,704
7
2011-05-31T06:20:25Z
6,183,731
16
2011-05-31T06:23:34Z
[ "python", "oop", "inheritance", "class-method" ]
I want to merge constraints from the current and inherited classes only once a class is loaded (not per object!). ``` class Domain(Validatable): constraints = {...} ``` To do this I defined a method `_initialize_class_not_instance` that should be called once for each class: ``` class Validatable: @classmet...
Use a metaclass. ``` class MetaClass(type): def __init__(cls, name, bases, d): type.__init__(cls, name, bases, d) cls.foo = 42 class MyClass(object): __metaclass__ = MetaClass print MyClass.foo ```
How to split large wikipedia dump .xml.bz2 files in Python?
6,184,912
4
2011-05-31T08:32:33Z
6,411,933
11
2011-06-20T13:30:52Z
[ "python", "xml", "mediawiki" ]
I am trying to build a offline wiktionary using the wikimedia dump files (.xml.bz2) using Python. I started with [this](http://users.softlab.ece.ntua.gr/~ttsiod/buildWikipediaOffline.html) article as the guide. It involves a number of languages, I wanted to combine all the steps as a single python project. I have found...
At last I have written a Python Script myself: ``` import os import bz2 def split_xml(filename): ''' The function gets the filename of wiktionary.xml.bz2 file as input and creates smallers chunks of it in a the diretory chunks ''' # Check and create chunk diretory if not os.path.exists("chunks"):...
How do i split a very long string into a list of shorter strings in python
6,186,746
2
2011-05-31T11:15:24Z
6,187,258
8
2011-05-31T12:00:10Z
[ "python", "django", "django-queryset", "python-2.6" ]
In my current django project I have a model that stores very long strings (can be 5000-10000 or even more characters per DB entry) and then i need to split them when a user is calling the record (it really need to be in one record in the DB). What i need is it to return a list (queryset? depends if in the "SQL" part or...
``` >>> s = "This is a very long string with many many many many and many more sentences and there is not one character that i can use to split by, just by number of words" >>> l = s.split() >>> n = 5 >>> [' '.join(l[x:x+n]) for x in xrange(0, len(l), n)] ['This is a very long', 'string with many many many', 'many an...
Python - How to use regexp on file, line by line, in Python
6,186,938
3
2011-05-31T11:34:56Z
6,186,991
9
2011-05-31T11:39:39Z
[ "python", "regex" ]
Tried to use different title for the question, but if you can improve the question, please do so. Here is my regexp: `f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)` I'd have to apply this on a file, line by line. The line by line is OK, simple reading from file, and a loop. But how do I apply the regexp to the lines? Thanks for ...
The following expression returns a list; every entry of that list contains all matches of your regexp in the respective line. ``` >>> import re >>> [re.findall(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)',line) for line in open('file.txt')] ```
How to convert integer value to array of four bytes in python
6,187,699
14
2011-05-31T12:39:03Z
6,187,741
20
2011-05-31T12:43:32Z
[ "python" ]
I need to send a message of bytes in Python and I need to convert an unsigned integer number to a byte array. How do you convert an integer value to an array of four bytes in Python? Like in C: ``` uint32_t number=100; array[0]=(number >>24) & 0xff; array[1]=(number >>16) & 0xff; array[2]=(number >>8) & 0xff; array[3]...
Have a look at the `struct` module. Probably all you need is `struct.pack("I", your_int)` to pack the integer in a string, and then place this string in the message. The format string `"I"` denotes an unsigned 32-bit integer. If you want to unpack such a string to a tuple of for integers, you can use `struct.unpack("4...
How to convert integer value to array of four bytes in python
6,187,699
14
2011-05-31T12:39:03Z
6,188,017
10
2011-05-31T13:05:22Z
[ "python" ]
I need to send a message of bytes in Python and I need to convert an unsigned integer number to a byte array. How do you convert an integer value to an array of four bytes in Python? Like in C: ``` uint32_t number=100; array[0]=(number >>24) & 0xff; array[1]=(number >>16) & 0xff; array[2]=(number >>8) & 0xff; array[3]...
[Sven](http://stackoverflow.com/questions/6187699/how-to-convert-integer-value-to-array-of-four-bytes-in-python/6187741#6187741) has you answer. However, byte shifting numbers (as in your question) is also possible in Python: ``` >>> [hex(0x12345678 >> i & 0xff) for i in (24,16,8,0)] ['0x12', '0x34', '0x56', '0x78'] `...
How to convert integer value to array of four bytes in python
6,187,699
14
2011-05-31T12:39:03Z
9,188,065
7
2012-02-08T05:01:24Z
[ "python" ]
I need to send a message of bytes in Python and I need to convert an unsigned integer number to a byte array. How do you convert an integer value to an array of four bytes in Python? Like in C: ``` uint32_t number=100; array[0]=(number >>24) & 0xff; array[1]=(number >>16) & 0xff; array[2]=(number >>8) & 0xff; array[3]...
In case anyone looks at this question sometime later ... This statement should be equivalent to the code in the original question: ``` >>> tuple( struct.pack("!I", number) ) ('\x00', '\x00', '\x00', 'd') ``` And I don't think it matters what the host byte order is. If your integers are larger than int32, you can ...
How to write a static python getitem method?
6,187,932
8
2011-05-31T12:59:39Z
6,187,986
19
2011-05-31T13:03:16Z
[ "python", "static", "operator-keyword", "magic-methods" ]
What do I need to change to make this work? ``` class A: @staticmethod def __getitem__(val): return "It works" print A[0] ``` Note that I am calling the `__getitem__` method on the type `A`. Thx in advance for any suggestions. If this question has already been asked once, my apologies, I could not ...
When an object is indexed, the special method `__getitem__` is looked for first in the object's class. A class itself is an object, and the class of a class is usually `type`. So to override `__getitem__` for a class, you can redefine its metaclass (to make it a subclass of `type`): ``` class MetaA(type): def __ge...
Choosing embedded scripting language for C++
6,188,798
9
2011-05-31T14:05:12Z
6,188,835
19
2011-05-31T14:08:40Z
[ "c++", "python", "ruby", "scripting", "lua" ]
I want to choose an embedded scripting language that i will use on C++. It should connect a database such as Oracle. My host application is a server application. That will pass raw data to script. The script will parse and do some specific logics. Also updates database. Then script will returns raw data as result. Can ...
[Lua](http://www.lua.org/) is intended to be an embedded language and has a [simple API](http://www.lua.org/manual/5.1/manual.html#3). Python and Ruby are much more general purpose and are (for embedding at least) significantly more complicated. This alone would lead me to using Lua.
Choosing embedded scripting language for C++
6,188,798
9
2011-05-31T14:05:12Z
6,188,989
11
2011-05-31T14:20:49Z
[ "c++", "python", "ruby", "scripting", "lua" ]
I want to choose an embedded scripting language that i will use on C++. It should connect a database such as Oracle. My host application is a server application. That will pass raw data to script. The script will parse and do some specific logics. Also updates database. Then script will returns raw data as result. Can ...
[Lua](http://www.lua.org/) is already mentioned and using [luabind](http://www.rasterbar.com/products/luabind.html) will give you a more c++ style interface. You could also take a look at [chaiscript](http://www.chaiscript.com/). It was more designed to fit into c++.
Choosing embedded scripting language for C++
6,188,798
9
2011-05-31T14:05:12Z
6,189,276
7
2011-05-31T14:39:36Z
[ "c++", "python", "ruby", "scripting", "lua" ]
I want to choose an embedded scripting language that i will use on C++. It should connect a database such as Oracle. My host application is a server application. That will pass raw data to script. The script will parse and do some specific logics. Also updates database. Then script will returns raw data as result. Can ...
Save this as test.c: ``` #include <Python.h> int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } ``` Run this command (if you have Python 2.7 installed): > gcc test.c -o te...
How to make a ssh connection with python?
6,188,970
8
2011-05-31T14:19:13Z
6,189,676
16
2011-05-31T15:09:46Z
[ "python" ]
Can anyone recommend something for making a ssh connection in python? I need it to be compatible with any OS. I've already tried pyssh only to get an error with SIGCHLD, which I've read is because Windows lacks this. I've tried getting paramiko to work, but I've had errors between paramiko and Crypto to the point wher...
The module pxssh does exactly what you want. For example, to run 'ls -l' and to print the output, you need to do something like that : ``` import pxssh s = pxssh.pxssh() if not s.login ('localhost', 'myusername', 'mypassword'): print "SSH session failed on login." print str(s) else: print "SSH session lo...
Easy way of finding decimal places
6,189,956
19
2011-05-31T15:31:59Z
6,190,236
9
2011-05-31T15:53:31Z
[ "python", "string", "decimal" ]
Is there an easy way or integrated function to find out the decimal places of a floating point number? The number is parsed from a string, so one way is to count the digits after the '.' sign, but that looks quite clumsy to me. Is there a possibility to get the information needed out of a `float` or `Decimal` object? ...
"the number of decimal places" is not really a property a floating point number has, because of the way they are stored and handled internally. You can get as many decimal places as you like from a floating point number. The question is how much accuracy you want. When converting a floating point number to a string, pa...
Easy way of finding decimal places
6,189,956
19
2011-05-31T15:31:59Z
6,190,291
22
2011-05-31T15:59:12Z
[ "python", "string", "decimal" ]
Is there an easy way or integrated function to find out the decimal places of a floating point number? The number is parsed from a string, so one way is to count the digits after the '.' sign, but that looks quite clumsy to me. Is there a possibility to get the information needed out of a `float` or `Decimal` object? ...
To repeat what others have said (because I had already typed it out!), I'm not even sure such a value would be meaningful in the case of a floating point number, because of the difference between the decimal and binary representation; often a number representable by a finite number of decimal digits will have only an i...
Python/Django debugging: print model's containing data
6,190,108
7
2011-05-31T15:44:05Z
6,190,203
11
2011-05-31T15:51:13Z
[ "python", "django", "debugging", "printing" ]
Maybe easy question but I don't know how to summarize it that I would find my answer. Is it possible to print out all available fields of model? For example in iPython I can import model and just write model name and tab will show all available fields the models have. Is it possible to do this in code without using ...
To check fields on a model I usually use `?`: ``` >>> Person? Type: ModelBase Base Class: <class 'django.db.models.base.ModelBase'> String Form: <class 'foo.bar.models.Person'> Namespace: Interactive File: /home/zk/ve/django/foo/bar/models.py Docstring: Person(id, first_name, last_name) ``` You ca...
Can I do an ordered, default dict in Python?
6,190,331
95
2011-05-31T16:02:12Z
6,190,500
50
2011-05-31T16:16:25Z
[ "python", "dictionary" ]
I would like to combine `OrderedDict()` and `defaultdict()` from `collections` in one object, which shall be an ordered, default dict. Is this possible?
The following (using a modified version of [this recipe](http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/)) works for me: ``` from collections import OrderedDict, Callable class DefaultOrderedDict(OrderedDict): # Source: http://stackoverflow.com/a/6190500/562769 def __init__(self, de...
Can I do an ordered, default dict in Python?
6,190,331
95
2011-05-31T16:02:12Z
6,193,884
8
2011-05-31T21:39:43Z
[ "python", "dictionary" ]
I would like to combine `OrderedDict()` and `defaultdict()` from `collections` in one object, which shall be an ordered, default dict. Is this possible?
Even though you've already accepted a solution, you might want to check-out the somewhat simpler `OrderedDefaultdict` class I wrote for this [answer](http://stackoverflow.com/questions/4126348/how-do-i-rewrite-this-function-to-implement-ordereddict/4127426#4127426).
Can I do an ordered, default dict in Python?
6,190,331
95
2011-05-31T16:02:12Z
30,742,547
7
2015-06-09T20:48:13Z
[ "python", "dictionary" ]
I would like to combine `OrderedDict()` and `defaultdict()` from `collections` in one object, which shall be an ordered, default dict. Is this possible?
Here's another solution to think about if your use case is simple like mine and you don't necessarily want to add the complexity of a `DefaultOrderedDict` class implementation to your code. ``` from collections import OrderedDict keys = ['a', 'b', 'c'] items = [(key, None) for key in keys] od = OrderedDict(items) ```...
Can I do an ordered, default dict in Python?
6,190,331
95
2011-05-31T16:02:12Z
35,968,897
12
2016-03-13T10:00:05Z
[ "python", "dictionary" ]
I would like to combine `OrderedDict()` and `defaultdict()` from `collections` in one object, which shall be an ordered, default dict. Is this possible?
Here is another possibility, inspired by [Raymond Hettinger's super() Considered Super](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/): ``` from collections import OrderedDict, defaultdict class OrderedDefaultDict(OrderedDict, defaultdict): def __init__(self, default_factory=None, *args, **k...
How to trigger function on value change?
6,190,468
13
2011-05-31T16:13:40Z
6,192,298
22
2011-05-31T19:08:12Z
[ "python", "event-handling", "observer-pattern" ]
I realise this question has to do with event-handling and i've read about Python event-handler a dispatchers, so either it did not answer my question or i completely missed out the information. I want method `m()` of object `A` to be triggered whenever value `v` is changing: For instance (assuming money makes happy):...
You need to use the [Observer Pattern](http://en.wikipedia.org/wiki/Observer_pattern). In the following code, a person subscribes to receive updates from the global wealth entity. When there is a change to global wealth, this entity then alerts all its subscribers (observers) that a change happened. Person then updates...
How to trigger function on value change?
6,190,468
13
2011-05-31T16:13:40Z
6,221,588
7
2011-06-02T23:42:09Z
[ "python", "event-handling", "observer-pattern" ]
I realise this question has to do with event-handling and i've read about Python event-handler a dispatchers, so either it did not answer my question or i completely missed out the information. I want method `m()` of object `A` to be triggered whenever value `v` is changing: For instance (assuming money makes happy):...
What are you looking for is called **[(Functional) Reactive Programming](http://en.wikipedia.org/wiki/Reactive_programming).** For Common Lisp there is Cells – see [Cells project](http://common-lisp.net/project/cells/) and [Cells manifesto](http://smuglispweeny.blogspot.com/2008/02/cells-manifesto.html) and for pytho...
What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check failes)?
6,190,776
61
2011-05-31T16:42:57Z
6,190,798
104
2011-05-31T16:44:39Z
[ "python", "function", "return" ]
Let's assume an iteration in which we call a function without a return value. The way I think my program should behave is explained in this pseudocode: ``` for element in some_list: foo(element) def foo(element): do something if check is true: do more (because check was succesful) else: ...
You could simply use ``` return ``` which does exactly the same as ``` return None ``` Your function will also return `None` if execution reaches the end of the function body without hitting a `return` statement. Returning nothing is the same as returning `None` in Python.
What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check failes)?
6,190,776
61
2011-05-31T16:42:57Z
6,190,808
9
2011-05-31T16:45:52Z
[ "python", "function", "return" ]
Let's assume an iteration in which we call a function without a return value. The way I think my program should behave is explained in this pseudocode: ``` for element in some_list: foo(element) def foo(element): do something if check is true: do more (because check was succesful) else: ...
I would suggest: ``` def foo(element): do something if not check: return do more (because check was succesful) do much much more... ```
Python Dictionary with List as Keys and Tuple as Values
6,190,868
5
2011-05-31T16:51:01Z
6,190,888
16
2011-05-31T16:52:53Z
[ "python", "list", "dictionary", "tuples" ]
I have a list that I want to use as the keys to a dictionary and a list of tuples with the values. Consider the following: ``` d = {} l = ['a', 'b', 'c', 'd', 'e'] t = [(1, 2, 3, 4), (7, 8, 9, 10), (4, 5, 6, 7), (9, 6, 3, 8), (7, 4, 1, 2)] for i in range(len(l)): d[l[i]] = t[i] ``` The list will consistently be ...
I did no timings, but probably ``` d = dict(zip(l, t)) ``` will be quite good. For only 5 key-value pairs, I don't think `izip()` will provide any advantage over `zip()`. The fact that each tuple has a lot of items does not matter for this operation, since the tuple objects are not copied at any point, neither with y...
Python Dictionary with List as Keys and Tuple as Values
6,190,868
5
2011-05-31T16:51:01Z
6,191,035
8
2011-05-31T17:08:22Z
[ "python", "list", "dictionary", "tuples" ]
I have a list that I want to use as the keys to a dictionary and a list of tuples with the values. Consider the following: ``` d = {} l = ['a', 'b', 'c', 'd', 'e'] t = [(1, 2, 3, 4), (7, 8, 9, 10), (4, 5, 6, 7), (9, 6, 3, 8), (7, 4, 1, 2)] for i in range(len(l)): d[l[i]] = t[i] ``` The list will consistently be ...
To build on Sven's [answer](http://stackoverflow.com/questions/6190868/python-dictionary-with-list-as-keys-and-tuple-as-values/6190888#6190888), using [`itertools.izip`](http://docs.python.org/library/itertools.html#itertools.izip) would be faster and use less memory if you needed to create a larger dict. With only fiv...
Python dictionary creation syntax
6,191,672
27
2011-05-31T18:11:01Z
6,191,780
40
2011-05-31T18:21:09Z
[ "python", "syntax", "dictionary" ]
I'm wondering if there's any way to populate a dictionary such that you have multiple keys mapping to the same value that's less verbose than say: ``` d = {1:'yes', 2:'yes', 3:'yes', 4:'no'} ``` I'm thinking something along the lines of: ``` d = {*(1,2,3):'yes', 4:'no'} ``` which is obviously a syntax error. Is th...
You could turn it around: ``` >>> d1 = {"yes": [1,2,3], "no": [4]} ``` and then "invert" that dictionary: ``` >>> d2 = {value:key for key in d1 for value in d1[key]} >>> d2 {1: 'yes', 2: 'yes', 3: 'yes', 4: 'no'} ```
Send log messages from all celery tasks to a single file
6,192,265
49
2011-05-31T19:05:00Z
6,193,082
88
2011-05-31T20:19:04Z
[ "python", "logging", "celery" ]
I'm wondering how to setup a more specific logging system. All my tasks use ``` logger = logging.getLogger(__name__) ``` as a module-wide logger. I want celery to log to "celeryd.log" and my tasks to "tasks.log" but I got no idea how to get this working. Using `CELERYD_LOG_FILE` from django-celery I can route all ce...
*Note: This answer is outdated as of Celery 3.0, where you now use [`get_task_logger()`](http://docs.celeryproject.org/en/latest/userguide/tasks.html#logging) to get your per-task logger set up. Please see [the Logging section of the What's new in Celery 3.0 document](http://docs.celeryproject.org/en/latest/whatsnew-3....
Pythonic way to find maximum value and its index in a list?
6,193,498
56
2011-05-31T21:00:40Z
6,193,521
78
2011-05-31T21:03:00Z
[ "python" ]
if I want maximum value, I can just write max(List), but what if I also need the index of the maximum value? I can write something like this: ``` maximum=0 for i,value in enumerate(List): if value>maximum: maximum=value index=i ``` But it looks tedious to me. And if I write: ``` List.index(max(...
There are many options, for example: ``` import operator index, value = max(enumerate(my_list), key=operator.itemgetter(1)) ```
Pythonic way to find maximum value and its index in a list?
6,193,498
56
2011-05-31T21:00:40Z
6,194,580
122
2011-05-31T23:09:52Z
[ "python" ]
if I want maximum value, I can just write max(List), but what if I also need the index of the maximum value? I can write something like this: ``` maximum=0 for i,value in enumerate(List): if value>maximum: maximum=value index=i ``` But it looks tedious to me. And if I write: ``` List.index(max(...
I think the accepted answer is great, but why don't you do it explicitly? I feel more people would understand your code, and that is in agreement with PEP 8: ``` max_value = max(my_list) max_index = my_list.index(max_value) ``` This method is also about three times faster than the accepted answer: ``` import random ...
How do Python properties work?
6,193,556
43
2011-05-31T21:06:35Z
6,193,590
7
2011-05-31T21:09:32Z
[ "python", "properties" ]
I've been successfully using Python properties, but I don't see how they could work. If I dereference a property outside of a class, I just get an object of type `property`: ``` @property def hello(): return "Hello, world!" hello # <property object at 0x9870a8> ``` But if I put a property in a class, the behavior i...
Properties are [descriptors](http://docs.python.org/howto/descriptor.html), and descriptors behave specially when member of a class instance. In short, if `a` is an instance of type `A`, and `A.foo` is a descriptor, then `a.foo` is equivalent to `A.foo.__get__(a)`.
How do Python properties work?
6,193,556
43
2011-05-31T21:06:35Z
6,193,656
33
2011-05-31T21:15:59Z
[ "python", "properties" ]
I've been successfully using Python properties, but I don't see how they could work. If I dereference a property outside of a class, I just get an object of type `property`: ``` @property def hello(): return "Hello, world!" hello # <property object at 0x9870a8> ``` But if I put a property in a class, the behavior i...
As others have noted, they use a language feature called descriptors. The reason that the actual property object is returned when you access it via a class `Hello.foo` lies in how the property implements the `__get__(self, instance, owner)` special method. If a descriptor is accessed on an *instance*, then that instan...
How do Python properties work?
6,193,556
43
2011-05-31T21:06:35Z
20,182,928
11
2013-11-25T00:24:05Z
[ "python", "properties" ]
I've been successfully using Python properties, but I don't see how they could work. If I dereference a property outside of a class, I just get an object of type `property`: ``` @property def hello(): return "Hello, world!" hello # <property object at 0x9870a8> ``` But if I put a property in a class, the behavior i...
In order for @properties to work properly the class needs to be a subclass of **object**. when the class is not a subclass of **object** then the first time you try access the setter it actually makes a new attribute with the shorter name instead of accessing through the setter. The following does **not** work correct...
Python readline from pipe on Linux
6,193,779
5
2011-05-31T21:28:02Z
6,193,800
8
2011-05-31T21:30:27Z
[ "python", "pipe", "readline" ]
When creating a pipe with `os.pipe()` it returns 2 file numbers; a read end and a write end which can be written to and read form with `os.write()`/`os.read()`; there is no os.readline(). Is it possible to use readline? ``` import os readEnd, writeEnd = os.pipe() # something somewhere writes to the pipe firstLine = re...
You can use [`os.fdopen()`](http://docs.python.org/2/library/os.html#os.fdopen) to get a file-like object from a file descriptor. ``` import os readEnd, writeEnd = os.pipe() readFile = os.fdopen(readEnd) firstLine = readFile.readline() ```
Scrapy image download how to use custom filename
6,194,041
11
2011-05-31T21:57:05Z
7,348,928
11
2011-09-08T13:35:56Z
[ "python", "scrapy" ]
For my [scrapy](http://doc.scrapy.org/index.html) project I'm currently using the [ImagesPipeline](http://doc.scrapy.org/topics/images.html#scrapy.contrib.pipeline.images.ImagesPipeline). The downloaded images are [stored with a SHA1 hash](http://doc.scrapy.org/topics/images.html#file-system-storage) of their URLs as t...
In scrapy 0.12 I solved something like this ``` class MyImagesPipeline(ImagesPipeline): #Name download version def image_key(self, url): image_guid = url.split('/')[-1] return 'full/%s.jpg' % (image_guid) #Name thumbnail version def thumb_key(self, url, thumb_id): image_guid =...
Scrapy image download how to use custom filename
6,194,041
11
2011-05-31T21:57:05Z
22,263,951
11
2014-03-08T01:48:16Z
[ "python", "scrapy" ]
For my [scrapy](http://doc.scrapy.org/index.html) project I'm currently using the [ImagesPipeline](http://doc.scrapy.org/topics/images.html#scrapy.contrib.pipeline.images.ImagesPipeline). The downloaded images are [stored with a SHA1 hash](http://doc.scrapy.org/topics/images.html#file-system-storage) of their URLs as t...
This is just actualization of the answer for scrapy 0.24 (EDITED), where the `image_key()` is deprecated ``` class MyImagesPipeline(ImagesPipeline): #Name download version def file_path(self, request, response=None, info=None): #item=request.meta['item'] # Like this you can use all from item, not just...
Using Python and Beautifulsoup how do I select the desired table in a div?
6,194,240
2
2011-05-31T22:21:02Z
6,194,304
8
2011-05-31T22:30:03Z
[ "python", "html-parsing", "beautifulsoup" ]
I would like to be able to select the table containing the "Accounts Payable" text but I'm not getting anywhere with what I'm trying and I'm pretty much guessing using findall. Can someone show me how I would do this? For example this is what I start with: ``` <div> <tr> <td class="lft lm">Accounts Payable </td> <td ...
You can select the *td* elements with class *lft lm* and then examine the element.string to determine if you have the "Accounts Payable" td: ``` import sys from BeautifulSoup import BeautifulSoup # where so_soup.txt is your html f = open ("so_soup.txt", "r") data = f.readlines () f.close () soup = BeautifulSoup (""....
pushd through os.system
6,194,499
10
2011-05-31T22:57:14Z
6,194,512
8
2011-05-31T22:58:52Z
[ "python", "cron", "centos" ]
I'm using a crontab to run a maintenance script for my minecraft server. Most of the time it works fine, unless the crontab tries to use the restart script. If I run the restart script manually, there aren't any issues. Because I believe it's got to do with path names, I'm trying to make sure it's always doing any mine...
Each shell command runs in a separate process. It spawns a shell, executes the pushd command, and then the shell exits. Just write the commands in the same shell script: ``` os.system("cd /directory/path/here; run the commands") ``` A nicer (perhaps) way is with the [`subprocess`](http://docs.python.org/library/subp...
pushd through os.system
6,194,499
10
2011-05-31T22:57:14Z
13,847,807
38
2012-12-12T20:11:22Z
[ "python", "cron", "centos" ]
I'm using a crontab to run a maintenance script for my minecraft server. Most of the time it works fine, unless the crontab tries to use the restart script. If I run the restart script manually, there aren't any issues. Because I believe it's got to do with path names, I'm trying to make sure it's always doing any mine...
In Python 2.5 and later, I think a better method would be using a context manager, like so: ``` from contextlib import contextmanager import os @contextmanager def pushd(newDir): previousDir = os.getcwd() os.chdir(newDir) yield os.chdir(previousDir) ``` You can then use it like the following: ``` wi...
Django create filter for nice time
6,194,589
6
2011-05-31T23:10:52Z
6,194,938
13
2011-06-01T00:13:08Z
[ "python", "django", "django-filter" ]
I know there's `timesince` filter. But I want something that returns this: * just few seconds ago * X minutes ago * X hours ago * on $day\_name * X weeks ago * X months ago Examples: * just few seconds ago * 37 minutes ago * 2 hours ago * yesterday * on Thursday * 1 week ago * 7 months ago How can I implement some...
Not sure if it ticks all your boxes, but there's a tag **naturaltime** in the django.contrib.humanize template tags that should do this: <https://docs.djangoproject.com/en/dev/ref/contrib/humanize/#naturaltime> **settings.py** ``` INSTALLED_APPS = { ... 'django.contrib.humanize', } ``` **template.html** ``...
Getting first image from html using Python/Django
6,194,875
3
2011-05-31T23:58:26Z
6,194,890
7
2011-06-01T00:02:29Z
[ "python", "html", "django", "image" ]
I am grabbing a bunch of html from a service and parsing it slightly. I am looking for a way to grab the link from the first image tag. Something similar like this JQuery code: ``` var imagelink = $('img:first', feed.content).attr('src'); ``` But of course using only Python/Django (server runs on Google app engine)....
You can use BeautifulSoup to do this: <http://www.crummy.com/software/BeautifulSoup/> It's a XML/HTML parser. So you pass in the raw html, and then you can search it for particular tags/attrs etc. something like this should work: ``` tree = BeautifulSoup(raw_html) img_link = (tree.find('img')[0]).attr['src'] ```
Django - how to set blank = False, required = False
6,194,988
7
2011-06-01T00:22:07Z
6,195,014
11
2011-06-01T00:27:03Z
[ "python", "django" ]
I've a model like this: ``` class Message(models.Model): msg = models.CharField(max_length = 150) ``` and I have a form for insert the field. Actually django allows empty spaces, for examples if I inset in the field one space it works. But now I want to fix this: the field is not required, but if a user insert a ...
[Whitespace](http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29) is not considered to be *blank*. *blank* specifically refers to *no input* (i.e. an empty string `''`). You will need to use a model field validator that raises an exception if the value only consists of spaces. See [the documentation](htt...
How to insert a checkbox in a django form
6,195,424
19
2011-06-01T01:46:40Z
6,195,447
25
2011-06-01T01:51:15Z
[ "python", "django", "django-forms" ]
I've a settings page where users can select if they want to receive a newsletter or not. I want a checkbox for this, and I want that Django select it if 'newsletter' is true in database. How can I implement in Django?
**models.py** ``` class Settings(model.Model): receive_newsletter = model.BooleanField() ... ``` **forms.py** ``` class SettingsForm(forms.ModelForm): receive_newsletter = forms.BooleanField() class Meta: model = Settings ``` If you want to automatically set receive\_newsletter to True acco...
References to methods C#
6,195,549
3
2011-06-01T02:13:31Z
6,195,557
7
2011-06-01T02:15:51Z
[ "c#", "python", "functional-programming" ]
I'm just wondering if there is a C# equivilent for this python code. I want to store the names of methods in some sort of collection and call them later on. I have searched, but I really don't know what to look for. For example in python I could do: ``` def add_one(x): return x + 1 def double_it(x): return x*2 m...
You are looking for [delegates](http://msdn.microsoft.com/en-us/library/ms173171.aspx). > A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke > (or call) the method through the delegate instanc...
IronPython: EXE compiled using pyc.py cannot import module "os"
6,195,781
18
2011-06-01T02:57:08Z
6,205,193
21
2011-06-01T17:21:39Z
[ "python", "ironpython" ]
I have a simple IronPython script: ``` # Foo.py import os def main(): print( "Hello" ) if "__main__" == __name__: main() ``` It runs fine and prints *Hello* if I run it with IronPython as: ``` ipy Foo.py ``` Following the instructions given in *[IronPython - how to compile exe](http://dbaportal.eu/2009/12...
Building an Ironpython EXE that you can distribute is a bit tricky - especially if you are using elements of the standard library. My typical solution is the following: I copy all of the stdlib modules I need into a folder (usually all of them just for completeness) and use this script to build my exe. In this example...
Jinja2: Render template inheritance?
6,195,805
10
2011-06-01T03:02:06Z
6,196,098
17
2011-06-01T03:56:22Z
[ "python", "extend", "jinja2" ]
I'd like to render a fused Jinja2 and Markdown page using a template, which looks like so: ``` {% block title %}{{ title }}{% endblock %} # {{ title[0] }} # {{ title[1] }} ## Introduction ``` I can get that above code to generate HTML fine, but as I am using this script for a custom authoring application, I'd like ...
Jinja's renderer needs to know how to load `template.html`, so you need to give the `Environment` a template loader instance. For example, assuming the files `page.html` and `template.html` are in the current directory: ``` from jinja import FileSystemLoader from jinja.environment import Environment env = Environmen...
About mysql cursor and iterator
6,195,988
16
2011-06-01T03:33:39Z
6,195,999
34
2011-06-01T03:36:54Z
[ "python", "mysql", "cursor", "fetchall" ]
Imagine I have a mysql cursor and data read. The amount of data might be very big that I want to deal with one line each time. An easy and straight forward way might be like this: ``` while True: row = cursor.fetchone() if not row: break ..... ``` but this doesn't look good, so I wonder whether this way ...
The `MySQLdb` cursor class implements the [iterator protocol](http://docs.python.org/reference/datamodel.html?highlight=__iter__#object.__iter__), so you can simply do this: ``` cursor.execute(sql) for row in cursor: print row ... ``` Relevant code from [MySQLdb.cursors.BaseCursor](http://mysql-python.svn.sou...
Flask message flashing fails across redirects
6,196,598
10
2011-06-01T05:15:28Z
6,208,784
10
2011-06-01T23:10:48Z
[ "python", "google-app-engine", "flask" ]
I'm currently working on a project using [Flask](http://en.wikipedia.org/wiki/Flask_%28programming%29) and [Google App Engine](http://en.wikipedia.org/wiki/Google_App_Engine). Calling `get_flashed_messages()` returns empty when I flash a message then use a `redirect()`: ``` @views.route('/todo/add', methods=["POST"]) ...
I got it! The trick is to set server name to something with dots. So 'localhost' became 'app.local' and app.local should be added to /etc/hosts, pointing to the same address as localhost. From the [docs](http://flask.pocoo.org/docs/0.10/config/#builtin-configuration-values): > Please keep in mind that not only > Fla...
Using WTForms' populate_obj( ) method with Flask micro framework
6,196,622
5
2011-06-01T05:18:40Z
6,209,167
13
2011-06-02T00:16:57Z
[ "python", "flask", "wtforms", "mongokit" ]
I have a template which allows the user to edit their user information. ``` <form method="post"> <table> <tr> <td>Username:</td> <td>{{user['username']}}</td> </tr> <tr> <td>New Password:</td> <td> <input type="password" name="password"></td> ...
`UserForm` should have `request.form` passed into it to populate it with the values available in the POST request (if any). ``` form = UserForm(request.form, obj=user) ```
Ordered Sets Python 2.7
6,197,409
8
2011-06-01T07:00:14Z
6,197,522
7
2011-06-01T07:11:41Z
[ "python", "list", "set", "order", "python-2.7" ]
I have a list that I'm attempting to remove duplicate items from. I'm using python 2.7.1 so I can simply use the **set()** function. However, this reorders my list. Which for my particular case is unacceptable. Below is a function I wrote; which does this. However I'm wondering if there's a better/faster way. Also any...
Use an OrderedDict: ``` from collections import OrderedDict l = ['a', 'a', 'a', 'b', 'b', 'c', 'd'] d = OrderedDict() for x in l: d[x] = True # prints a b c d for x in d: print x, print ```
Ordered Sets Python 2.7
6,197,409
8
2011-06-01T07:00:14Z
6,197,827
10
2011-06-01T07:44:41Z
[ "python", "list", "set", "order", "python-2.7" ]
I have a list that I'm attempting to remove duplicate items from. I'm using python 2.7.1 so I can simply use the **set()** function. However, this reorders my list. Which for my particular case is unacceptable. Below is a function I wrote; which does this. However I'm wondering if there's a better/faster way. Also any...
Another very fast method with set: ``` def remove_duplicates(lst): dset = set() # relies on the fact that dset.add() always returns None. return [ l for l in lst if l not in dset and not dset.add(l) ] ```
Ordered Sets Python 2.7
6,197,409
8
2011-06-01T07:00:14Z
6,197,964
7
2011-06-01T07:56:52Z
[ "python", "list", "set", "order", "python-2.7" ]
I have a list that I'm attempting to remove duplicate items from. I'm using python 2.7.1 so I can simply use the **set()** function. However, this reorders my list. Which for my particular case is unacceptable. Below is a function I wrote; which does this. However I'm wondering if there's a better/faster way. Also any...
Assuming the input sequence is unordered, here's `O(N)` solution (both in space and time). It produces a sequence with duplicates removed, while leaving unique items in the same relative order as they appeared in the input sequence. ``` >>> def remove_dups_stable(s): ... seen = set() ... for i in s: ... if i n...
Most Pythonic way to provide global configuration variables in config.py?
6,198,372
28
2011-06-01T08:35:24Z
6,199,300
26
2011-06-01T09:52:12Z
[ "global-variables", "python", "config", "egg" ]
In my endless quest in over-complicating simple stuff, I am researching the most 'Pythonic' way to provide global configuration variables inside the typical '**config.py**' found in Python egg packages. The traditional way (aah, good ol' *#define*!) is as follows: ``` MYSQL_PORT = 3306 MYSQL_DATABASE = 'mydb' MYSQL_D...
How about just using the built-in types like this: ``` config = { "mysql": { "user": "root", "pass": "secret", "tables": { "users": "tb_users" } # etc } } ``` You'd access the values as follows: ``` config["mysql"]["tables"]["users"] ``` --- If you are wi...
How do I change nesting function's variable in the nested function
6,198,709
15
2011-06-01T09:05:54Z
6,198,753
19
2011-06-01T09:09:11Z
[ "python", "global-variables", "nested-function" ]
I'd like to have variable defined in the nesting function to be altered in the nested function, something like ``` def nesting(): count = 0 def nested(): count += 1 for i in range(10): nested() print count ``` When nesting function is called, I wish it prints 10, but it raises Unbound...
In Python 3.x, you can use the `nonlocal` declaration (in `nested`) to tell Python you mean to assign to the `count` variable in `nesting`. In Python 2.x, you simply can't assign to `count` in `nesting` from `nested`. However, you *can* work around it by not assigning to the variable itself, but using a mutable contai...
Deciding which exceptions to catch in Python
6,199,884
7
2011-06-01T10:42:42Z
6,199,942
10
2011-06-01T10:48:27Z
[ "python", "exception-handling" ]
Suppose that I am using a library `X` that specifies for example that `exception.BaseError` is the base class for all exceptions of `X`. Now, there is another exception, say `X.FooError`, which of course inherits from `exception.BaseError` but is more generalized, let's say that it handles invalid input. Let's suppose...
Catch only the exceptions you can handle. If you can handle both the base exception and the derived exception then catch both. But make sure to put the derived exception first, since the first exception handler found that matches is the one used. ``` try: X.foo() except X.FooError: pass except X.BaseError: pass ...