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
Interpolation in SciPy: Finding X that produces Y
1,029,207
11
2009-06-22T20:20:59Z
1,031,510
15
2009-06-23T09:25:18Z
[ "python", "numpy", "scipy", "interpolation", "scientific-computing" ]
Is there a better way to find which *X* gives me the *Y* I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function. ``` import numpy as np import matplotlib.pyplot as plt from scipy import interpolate x = [70, 80, 90, 100, 110] y = [49.7, 80.6, 122.5, 153.8, 163.0] tck = interpo...
The UnivariateSpline class in scipy makes doing splines much more pythonic. ``` x = [70, 80, 90, 100, 110] y = [49.7, 80.6, 122.5, 153.8, 163.0] f = interpolate.UnivariateSpline(x, y, s=0) xnew = np.arange(70,111,1) plt.plot(x,y,'x',xnew,f(xnew)) ``` To find x at y then do: ``` yToFind = 140 yreduced = np.array(y) ...
Calling a hook function every time an Exception is raised
1,029,318
9
2009-06-22T20:49:39Z
1,029,342
11
2009-06-22T20:56:13Z
[ "python", "exception" ]
Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. Of course, this could be generalized to being able to insert a hook every time an exception is raised. Would the following code be considered safe for doing such a thing? `...
If you want to log *uncaught* exceptions, just use [sys.excepthook](http://docs.python.org/library/sys.html). I'm not sure I see the value of logging *all* raised exceptions, since lots of libraries will raise/catch exceptions internally for things you probably won't care about.
Holiday files for G20 countries
1,029,794
10
2009-06-22T22:51:25Z
21,462,251
16
2014-01-30T16:39:01Z
[ "python", "finance" ]
For proper financial FX option pricing I require the exact number of *business* days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to G20 countr...
I recently came across <https://github.com/novapost/workalendar>. I use it for France and it works like a charm. ``` """ >>> from datetime import date >>> from workalendar.europe import France >>> cal = France() >>> cal.holidays(2013) [(datetime.date(2013, 1, 1), 'New year'), (datetime.date(2013, 4, 1), 'Easter Monda...
python, unittest: is there a way to pass command line options to the app
1,029,891
30
2009-06-22T23:23:05Z
1,029,923
28
2009-06-22T23:37:01Z
[ "python", "unit-testing" ]
I have a module that imports unittest and has some TestCases. I would like to accept some command line options (for example below, the name of a data file), but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using optpa...
In your `if __name__ == '__main__':` section, which you're not showing us, you'll need to `optparse` and then `del sys.argv[1:]` before you pass control to `unittest` code, so that the latter code doesn't try to interpret your command line options *again* when you've already dealt with them. (It's a bit harder to have ...
python, unittest: is there a way to pass command line options to the app
1,029,891
30
2009-06-22T23:23:05Z
8,660,290
33
2011-12-28T19:23:36Z
[ "python", "unit-testing" ]
I have a module that imports unittest and has some TestCases. I would like to accept some command line options (for example below, the name of a data file), but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using optpa...
Building on Alex's answer, it's actually pretty easy to do using [`argparse`](http://docs.python.org/library/argparse.html): ``` if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', default='My Input') parser.add_argument('filename', default='some_file.txt') pars...
Formatting with mako
1,029,965
2
2009-06-22T23:51:31Z
1,029,975
7
2009-06-22T23:53:51Z
[ "python", "template-engine", "mako" ]
Anyone know how to format the length of a string with Mako? The equivalent of *print "%20s%10s" % ("string 1", "string 2")*?
you can use python's string formatting fairly easily in mako ``` ${"%20s%10s" % ("string 1", "string 2")} ``` giving: ``` >>> from mako.template import Template >>> Template('${"%20s%10s" % ("string 1", "string 2")}').render() ' string 1 string 2' ```
Calling an external program from python
1,030,114
3
2009-06-23T00:51:14Z
1,030,227
8
2009-06-23T01:36:00Z
[ "python", "c" ]
So I have this shell script: ``` echo "Enter text to be classified, hit return to run classification." read text if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ] then echo "Text is not likely to be stupid." fi if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf...
To do it just like the shell script does: ``` import subprocess text = raw_input("Enter text to be classified: ") p1 = subprocess.Popen('bin/stupidfilter', 'data/c_trbf') stupid = float(p1.communicate(text)[0]) if stupid: print "Text is likely to be stupid" else: print "Text is not likely to be stupid" ```
Race conditions in django
1,030,270
26
2009-06-23T01:53:37Z
1,030,464
8
2009-06-23T03:09:14Z
[ "python", "database", "django", "locking", "race-condition" ]
Here is a simple example of a django view with a potential race condition: ``` # myapp/views.py from django.contrib.auth.models import User from my_libs import calculate_points def add_points(request): user = request.user user.points += calculate_points(user) user.save() ``` The race condition should be ...
Database locking is the way to go here. There are plans to add "select for update" support to Django ([here](http://code.djangoproject.com/ticket/2705)), but for now the simplest would be to use raw SQL to UPDATE the user object before you start to calculate the score. --- Pessimistic locking is now supported by Djan...
Race conditions in django
1,030,270
26
2009-06-23T01:53:37Z
1,955,721
11
2009-12-23T22:40:34Z
[ "python", "database", "django", "locking", "race-condition" ]
Here is a simple example of a django view with a potential race condition: ``` # myapp/views.py from django.contrib.auth.models import User from my_libs import calculate_points def add_points(request): user = request.user user.points += calculate_points(user) user.save() ``` The race condition should be ...
As of Django 1.1 you can use the ORM's F() expressions to solve this specific problem. ``` from django.db.models import F user = request.user user.points = F('points') + calculate_points(user) user.save() ``` For more details see the documentation: <https://docs.djangoproject.com/en/1.8/ref/models/instances/#updat...
Race conditions in django
1,030,270
26
2009-06-23T01:53:37Z
10,987,224
33
2012-06-11T20:41:10Z
[ "python", "database", "django", "locking", "race-condition" ]
Here is a simple example of a django view with a potential race condition: ``` # myapp/views.py from django.contrib.auth.models import User from my_libs import calculate_points def add_points(request): user = request.user user.points += calculate_points(user) user.save() ``` The race condition should be ...
Django 1.4+ supports [select\_for\_update](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.select_for_update), in earlier versions you may execute raw SQL queries e.g. `select ... for update` which depending on underlying DB will lock the row from any updates, you can do what...
Simple User management example for Google App Engine?
1,030,293
17
2009-06-23T01:58:46Z
1,033,333
22
2009-06-23T15:33:11Z
[ "php", "python", "google-app-engine" ]
I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whole t...
I tend to use my own user and session manangement For my web handlers I will attach a decorator called `session` and one called `authorize`. The `session` decorator will attach a session to every request, and the `authorize` decorator will make sure that the user is authorised. (A word of caution, the authorize decor...
what is python equivalent to PHP $_SERVER?
1,031,192
6
2009-06-23T07:55:52Z
1,031,259
11
2009-06-23T08:10:20Z
[ "php", "python" ]
I couldn't find out python equivalent to PHP $\_SERVER. Is there any? Or, what are the methods to bring equivalent results? Thanks in advance.
Using **mod\_wsgi**, which I would recommend over mod\_python (long story but trust me) ... Your application is passed an **environment** variable such as: ``` def application(environ, start_response): ... ``` And the environment contains typical elements from $\_SERVER in PHP ``` ... environ['REQUEST_URI']; ......
Python/Django or C#/ASP.NET for web development?
1,031,438
7
2009-06-23T09:01:30Z
1,031,492
13
2009-06-23T09:21:42Z
[ "asp.net", "python", "django", "scalability" ]
I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us. Thank you.
Almost all the well known frameworks and languages can scale. It doesn't really matter which one you use. Its about how well you structure the code that matters most. On a personal level it is always good to know more than one language. But, you can create perfectly scalable Python, PHP, .NET applications. The quali...
Python/Django or C#/ASP.NET for web development?
1,031,438
7
2009-06-23T09:01:30Z
1,036,216
14
2009-06-24T03:05:07Z
[ "asp.net", "python", "django", "scalability" ]
I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us. Thank you.
Much as I love Python (and, that's a LOT!-), if you're highly skilled at C# and, as you say, "have no experience on Python", *your* code will be more scalable and suitable (for the next several months, at least) if you stick with what you know best. For a hypothetical developer extremely skilled at both platforms, scal...
Profiling self and arguments in python?
1,031,657
3
2009-06-23T10:02:41Z
1,031,724
11
2009-06-23T10:21:31Z
[ "python", "profiling" ]
How do I profile a call that involves self and arguments in python? ``` def performProfile(self): import cProfile self.profileCommand(1000000) def profileCommand(self, a): for i in a: pass ``` In the above example how would I profile just the call to profileCommand? I figured out I need to use ru...
you need to pass locals/globals dict and pass first argument what you will usually type e.g. ``` cProfile.runctx("self.profileCommand(100)", globals(),locals()) ``` use something like this ``` class A(object): def performProfile(self): import cProfile cProfile.runctx("self.profileCommand(100)", g...
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
1,031,860
10
2009-06-23T10:55:34Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
`res = dict(zip(a.values(), a.keys()))`
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
1,031,878
51
2009-06-23T11:00:16Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
``` res = dict((v,k) for k,v in a.iteritems()) ```
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
1,031,887
16
2009-06-23T11:02:07Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
You could try: ``` d={'one':1,'two':2} d2=dict((value,key) for key,value in d.iteritems()) d2 {'two': 2, 'one': 1} ``` Beware that you cannot 'reverse' a dictionary if 1. More than one key shares the same value. For example `{'one':1,'two':1}`. The new dictionary can only have one item with key `1`. 2. One or more...
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
1,087,700
30
2009-07-06T15:43:30Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
``` In [1]: my_dict = {'x':1, 'y':2, 'z':3} In [2]: dict((value, key) for key, value in my_dict.iteritems()) Out[2]: {1: 'x', 2: 'y', 3: 'z'} ```
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
1,087,723
13
2009-07-06T15:46:48Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
``` new_dict = dict( (my_dict[k], k) for k in my_dict) ``` or even better, but only works in Python 3: ``` new_dict = { my_dict[k]: k for k in my_dict} ```
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
1,087,838
44
2009-07-06T16:09:46Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
``` new_dict = dict (zip(my_dict.values(),my_dict.keys())) ```
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
1,087,957
29
2009-07-06T16:36:39Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
From Python 2.7 on, including 3.0+, there's an arguably shorter, more readable version: ``` >>> my_dict = {'x':1, 'y':2, 'z':3} >>> {v: k for k, v in my_dict.items()} {1: 'x', 2: 'y', 3: 'z'} ```
Python: Best Way to Exchange Keys with Values in a Dictionary?
1,031,851
28
2009-06-23T10:53:12Z
18,043,402
15
2013-08-04T13:21:19Z
[ "python", "dictionary" ]
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique. For example, say my input is: ``` a = dict() a['one']=1 a['two']=2 ``` I would like my output to be: ``` {1: 'one', 2: 'two'} ``` ...
You can make use of [dict comprehensions](http://www.python.org/dev/peps/pep-0274/): ``` res = {v : k for k, v in a.iteritems()} ```
wxPython: Good way to overlay a wx.Panel on an existing wx.Panel
1,032,138
4
2009-06-23T12:04:54Z
1,032,282
10
2009-06-23T12:36:25Z
[ "python", "user-interface", "wxpython" ]
I have a wx.Frame, in which there is a main wx.Panel with several widgets inside of it. I want one button in there to cause a "help panel" to come up. This help panel would probably be a wx.Panel, and I want it to overlay the entire main wx.Panel (not including the menu bar of the wx.Frame). There should be some sort o...
There are several ways a) you can create a custom child panel, and make it same size and position at 0,0 among top of all child widgets. no need of destroying it just Show/Hide it this also resizes with parent frame b) popup a wx.PopupWindow or derived class and place and size it at correct location so as suggest in...
Python: finding keys with unique values in a dictionary?
1,032,281
14
2009-06-23T12:35:47Z
1,032,444
12
2009-06-23T13:02:44Z
[ "python", "dictionary" ]
I receive a dictionary as input, and want to return a list of keys for which the dictionary values are unique in the scope of that dictionary. I will clarify with an example. Say my input is dictionary a, constructed as follows: ``` a = dict() a['cat'] = 1 a['fish'] = 1 a['dog'] = 2 # <-- unique a['bat...
I think efficient way if dict is too large would be ``` countMap = {} for v in a.itervalues(): countMap[v] = countMap.get(v,0) + 1 uni = [ k for k, v in a.iteritems() if countMap[v] == 1] ```
Python Formatter Tool
1,032,393
24
2009-06-23T12:53:52Z
1,502,993
14
2009-10-01T09:55:50Z
[ "python", "formatter" ]
I was wondering if there exists a sort of Python beautifier like the gnu-indent command line tool for C code. Of course indentation is not the point in Python since it is programmer's responsibility but I wish to get my code written in a perfectly homogenous way, taking care particularly of having always identical blan...
I am the one who asks the question. In fact, the tool the closest to my needs seems to be [PythonTidy](http://www.lacusveris.com/PythonTidy/) (it's a Python program of course : Python is best served by himself ;) ).
Check if only one variable in a list of variables is set
1,032,411
9
2009-06-23T12:56:22Z
1,032,442
15
2009-06-23T13:02:34Z
[ "python", "xor" ]
I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this [logical xor post](http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python) and is trying to find a way to adapt to multiple variables and only one true....
There isn't one built in but it's not to hard to roll you own: ``` def TrueXor(*args): return sum(args) == 1 ``` Since "[b]ooleans are a subtype of plain integers" ([source](http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex)) you can sum the list of integers quite easily and you ca...
Check if only one variable in a list of variables is set
1,032,411
9
2009-06-23T12:56:22Z
1,033,153
7
2009-06-23T15:07:06Z
[ "python", "xor" ]
I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this [logical xor post](http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python) and is trying to find a way to adapt to multiple variables and only one true....
I think the sum-based solution is fine for the given example, but keep in mind that boolean predicates in python always short-circuit their evaluation. So you might want to consider something more consistent with [all and any](http://docs.python.org/library/functions.html#all). ``` def any_one(iterable): it = iter...
using two for loops in python
1,032,722
3
2009-06-23T13:57:41Z
1,032,895
8
2009-06-23T14:26:16Z
[ "python", "for-loop", "combinations" ]
I have started to learn python recently and have a question about for loops that I was hoping someone could answer. I want to be able to print all the possible products of two numbers from one to ten. so: 2 by 2, 2 by 3, 2 by 4...2 by 10, 3 by 2, 3 by 3...3 by 10, 4 by 2, 4 by 3 etc...I would have thought the easiest w...
Here is another way ``` a = [i*j for i in xrange(1,11) for j in xrange(i,11)] ``` **note** we need to start second iterator from 'i' instead of 1, so this is doubly efficient edit: proof that it is same as simple solution ``` b = [] for i in range(1,11): for j in range(1,11): b.append(i*j) print set(a)...
Dump stacktraces of all active Threads
1,032,813
19
2009-06-23T14:13:38Z
1,032,930
7
2009-06-23T14:31:33Z
[ "python", "multithreading", "plone", "zope" ]
I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I ha...
2.4. Too bad. From Python 2.5 on there is `sys._current_frames()`. But you could try [threadframe](http://www.majid.info/mylos/stories/2004/06/10/threadframe.html). And if the makefile gives you trouble you could try this [setup.py for threadframe](http://www.wsanchez.net/blog/2004/06/stack_traces_in_python_threads.ht...
Dump stacktraces of all active Threads
1,032,813
19
2009-06-23T14:13:38Z
7,317,379
27
2011-09-06T09:02:15Z
[ "python", "multithreading", "plone", "zope" ]
I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I ha...
As jitter points out in an earlier answer `sys._current_frames()` gives you what you need for v2.5+. For the lazy the following code snippet worked for me and may help you: ``` print >> sys.stderr, "\n*** STACKTRACE - START ***\n" code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# Thr...
Dump stacktraces of all active Threads
1,032,813
19
2009-06-23T14:13:38Z
24,334,576
8
2014-06-20T19:46:18Z
[ "python", "multithreading", "plone", "zope" ]
I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there. Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I ha...
For Python 3.3 and later, there is [`faulthandler.dump_traceback()`](https://docs.python.org/3/library/faulthandler.html#dumping-the-traceback). The code below produces similar output, but includes the thread name and could be enhanced to print more information. ``` for th in threading.enumerate(): print(th) ...
How to remove bad path characters in Python?
1,033,424
13
2009-06-23T15:45:39Z
1,033,669
9
2009-06-23T16:21:28Z
[ "python", "path" ]
What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python? ### Solution Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code: ``` def remove(value, deletechars): for c in deletechars: value = val...
Unfortunately, the set of acceptable characters varies by OS *and* by filesystem. * [Windows](http://msdn.microsoft.com/en-us/library/aa365247.aspx): > + Use almost any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for th...
How to remove bad path characters in Python?
1,033,424
13
2009-06-23T15:45:39Z
13,593,932
7
2012-11-27T22:01:10Z
[ "python", "path" ]
What is the most cross platform way of removing bad path characters (e.g. "\" or ":" on Windows) in Python? ### Solution Because there seems to be no ideal solution I decided to be relatively restrictive and did use the following code: ``` def remove(value, deletechars): for c in deletechars: value = val...
I think the safest approach here is to just replace any suspicious characters. So, I think you can just replace (or get rid of) anything that isn't alphanumeric, -, \_, a space, or a period. And here's how you do that: ``` import re re.sub('[^\w\-_\. ]', '_', filename) ``` The above escapes every character that's not...
python class attribute inheritance
1,033,443
2
2009-06-23T15:47:56Z
1,033,516
7
2009-06-23T15:59:32Z
[ "python", "django", "class", "inheritance" ]
I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this: ``` class lgrAdminObject(admin.ModelAdmin): fields = ["title","owner"] list_display = ["title","origin","approved", "sendToFrames"] class Photos(lgrAdminObject): fields.extend(["albums"]) ``` why doesn...
Inheritance applies *after* the class's body executes. In the class body, you can use `lgrAdminObject.fields` -- you sure you want to alter the superclass's attribute rather than making a copy of it first, though? Seems peculiar... I'd start with a copy: ``` class Photos(lgrAdminObject): fields = list(lgrAdminObje...
Python package install using pip or easy_install from repos
1,033,897
14
2009-06-23T17:07:30Z
1,034,006
11
2009-06-23T17:32:22Z
[ "python", "svn", "version-control", "easy-install", "pip" ]
The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder. Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very ...
If you download or check out the source distribution of a package — the one that has its "setup.py" inside of it — then if the package is based on the "setuptools" (which also power easy\_install), you can move into that directory and say: ``` $ python setup.py develop ``` and it will create the right symlinks in...
Python package install using pip or easy_install from repos
1,033,897
14
2009-06-23T17:07:30Z
1,625,662
26
2009-10-26T16:08:10Z
[ "python", "svn", "version-control", "easy-install", "pip" ]
The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder. Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very ...
Using [pip](http://pip.openplans.org/) this is quite easy. For instance: ``` pip install -e hg+http://bitbucket.org/andrewgodwin/south/#egg=South ``` Pip will automatically clone the source repo and run "setup.py develop" for you to install it into your environment (which hopefully is a [virtualenv](http://pypi.pytho...
Per-session transactions in Django
1,033,934
7
2009-06-23T17:16:29Z
1,033,973
9
2009-06-23T17:24:42Z
[ "python", "django", "transactions" ]
I'm making a Django web-app which allows a user to build up a set of changes over a series of GETs/POSTs before committing them to the database (or reverting) with a final POST. I have to keep the updates isolated from any concurrent database users until they are confirmed (this is a configuration front-end), ruling ou...
Multiple, concurrent, session-scale transactions will generally lead to deadlocks or worse (worse == livelock, long delays while locks are held by another session.) This design is not the best policy, which is why Django discourages it. The better solution is the following. 1. Design a **Memento** class that records...
wxPython: Making something expand
1,034,399
4
2009-06-23T18:46:44Z
1,034,455
8
2009-06-23T18:55:11Z
[ "python", "user-interface", "wxpython" ]
How do I make any wxPython widget (like wx.Panel or wx.Button) automatically expand to fill its parent window?
The short answer: use a sizer with a proportion of 1 and the wx.Expand tag. So here I am in the **init** of a panel ``` sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) self.SetSizer(sizer) ```
Python: most idiomatic way to convert None to empty string?
1,034,573
69
2009-06-23T19:17:29Z
1,034,598
91
2009-06-23T19:21:12Z
[ "string", "python", "idioms" ]
What is the most idiomatic way to do the following? ``` def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) ``` **update:** I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vina...
``` def xstr(s): return '' if s is None else str(s) ```
Python: most idiomatic way to convert None to empty string?
1,034,573
69
2009-06-23T19:17:29Z
1,034,633
39
2009-06-23T19:28:18Z
[ "string", "python", "idioms" ]
What is the most idiomatic way to do the following? ``` def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) ``` **update:** I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vina...
If you actually want your function to behave like the `str()` built-in, but return an empty string when the argument is None, do this: ``` def xstr(s): if s is None: return '' return str(s) ```
Python: most idiomatic way to convert None to empty string?
1,034,573
69
2009-06-23T19:17:29Z
1,035,497
64
2009-06-23T22:01:12Z
[ "string", "python", "idioms" ]
What is the most idiomatic way to do the following? ``` def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) ``` **update:** I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vina...
If you know that the value will always either be a string or None: ``` xstr = lambda s: s or "" print xstr("a") + xstr("b") # -> 'ab' print xstr("a") + xstr(None) # -> 'a' print xstr(None) + xstr("b") # -> 'b' print xstr(None) + xstr(None) # -> '' ```
Python: most idiomatic way to convert None to empty string?
1,034,573
69
2009-06-23T19:17:29Z
1,036,222
38
2009-06-24T03:08:53Z
[ "string", "python", "idioms" ]
What is the most idiomatic way to do the following? ``` def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) ``` **update:** I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vina...
`return s or ''` will work just fine for your stated problem!
Python: most idiomatic way to convert None to empty string?
1,034,573
69
2009-06-23T19:17:29Z
1,036,316
11
2009-06-24T03:56:07Z
[ "string", "python", "idioms" ]
What is the most idiomatic way to do the following? ``` def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) ``` **update:** I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vina...
``` def xstr(s): return s or "" ```
Python: most idiomatic way to convert None to empty string?
1,034,573
69
2009-06-23T19:17:29Z
12,215,416
28
2012-08-31T12:28:40Z
[ "string", "python", "idioms" ]
What is the most idiomatic way to do the following? ``` def xstr(s): if s is None: return '' else: return s s = xstr(a) + xstr(b) ``` **update:** I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vina...
Probably the shortest would be `str(s or '')` Because None is False, and "x or y" returns y if x is false. See [Boolean Operators](http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not) for a detailed explanation. It's short, but not very explicit.
Finding Nth item of unsorted list without sorting the list
1,034,846
15
2009-06-23T20:04:41Z
1,034,886
13
2009-06-23T20:12:07Z
[ "python", "arrays", "sorting" ]
Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...
Sorting would require O(nlogn) runtime at minimum - There are very efficient [selection algorithms](http://en.wikipedia.org/wiki/Quick%5Fselect) which can solve your problem in linear time. `Partition-based selection` (sometimes `Quick select`), which is based on the idea of quicksort (recursive partitioning), is a go...
Finding Nth item of unsorted list without sorting the list
1,034,846
15
2009-06-23T20:04:41Z
1,036,240
18
2009-06-24T03:21:47Z
[ "python", "arrays", "sorting" ]
Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...
A heap is the best data structure for this operation and Python has an excellent built-in library to do just this, called heapq. ``` import heapq def nth_largest(n, iter): return heapq.nlargest(n, iter)[-1] ``` Example Usage: ``` >>> import random >>> iter = [random.randint(0,1000) for i in range(100)] >>> n = ...
How can I create a Word document using Python?
1,035,183
32
2009-06-23T20:59:08Z
1,035,392
33
2009-06-23T21:36:24Z
[ "python", "xml", "xslt", "ms-word" ]
I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I [programatically convert](http://www.xhtml2pdf.com/) to a PDF file. However, my client is now requesting that the same docume...
A couple ways you can create Word documents using Python: * Use COM automation to create a document using the MS Word object model (using `pywin32`). <http://python.net/crew/pirx/spam7/> * Automate OpenOffice using Python: <http://wiki.services.openoffice.org/wiki/Python> * If rtf format is OK, use the PyRTF library: ...
How can I create a Word document using Python?
1,035,183
32
2009-06-23T20:59:08Z
8,052,336
19
2011-11-08T14:54:21Z
[ "python", "xml", "xslt", "ms-word" ]
I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I [programatically convert](http://www.xhtml2pdf.com/) to a PDF file. However, my client is now requesting that the same docume...
I tried [python-docx](https://github.com/mikemaccana/python-docx) with succes, it enables you to make and edit docx within Python
Reading binary file in Python and looping over each byte
1,035,340
198
2009-06-23T21:26:52Z
1,035,360
196
2009-06-23T21:31:28Z
[ "python", "file-io", "binary" ]
In Python, how do I read in a binary file and loop over each byte of that file?
``` f = open("myfile", "rb") try: byte = f.read(1) while byte != "": # Do stuff with byte. byte = f.read(1) finally: f.close() ``` By suggestion of chrispy: ``` with open("myfile", "rb") as f: byte = f.read(1) while byte != "": # Do stuff with byte. byte = f.read(1)...
Reading binary file in Python and looping over each byte
1,035,340
198
2009-06-23T21:26:52Z
1,035,419
37
2009-06-23T21:43:03Z
[ "python", "file-io", "binary" ]
In Python, how do I read in a binary file and loop over each byte of that file?
If the file is not too big that holding it in memory is a problem: ``` bytes_read = open("filename", "rb").read() for b in bytes_read: process_byte(b) ``` where process\_byte represents some operation you want to perform on the passed-in byte. If you want to process a chunk at a time: ``` file = open("filename"...
Reading binary file in Python and looping over each byte
1,035,340
198
2009-06-23T21:26:52Z
1,035,456
109
2009-06-23T21:50:55Z
[ "python", "file-io", "binary" ]
In Python, how do I read in a binary file and loop over each byte of that file?
This generator yields bytes from a file, reading the file in chunks: ``` def bytes_from_file(filename, chunksize=8192): with open(filename, "rb") as f: while True: chunk = f.read(chunksize) if chunk: for b in chunk: yield b else: ...
Reading binary file in Python and looping over each byte
1,035,340
198
2009-06-23T21:26:52Z
18,652,697
13
2013-09-06T07:55:55Z
[ "python", "file-io", "binary" ]
In Python, how do I read in a binary file and loop over each byte of that file?
To sum up all the brilliant points of chrispy, Skurmedel, Ben Hoyt and Peter Hansen, this would be the optimal solution for processing a binary file one byte at a time: ``` with open("myfile", "rb") as f: while True: byte = f.read(1) if not byte: break do_stuff_with(ord(byte)) `...
Reading binary file in Python and looping over each byte
1,035,340
198
2009-06-23T21:26:52Z
20,014,805
16
2013-11-16T04:47:57Z
[ "python", "file-io", "binary" ]
In Python, how do I read in a binary file and loop over each byte of that file?
To read a file — one byte at a time (ignoring the buffering) — you could use the [two-argument `iter(callable, sentinel)` built-in function](http://docs.python.org/2/library/functions.html#iter): ``` from functools import partial with open(filename, 'rb') as file: for byte in iter(partial(file.read, 1), b''):...
Python garbage collection
1,035,489
23
2009-06-23T21:59:01Z
1,035,512
16
2009-06-23T22:07:41Z
[ "python", "optimization", "memory-management", "garbage-collection" ]
I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?
You haven't provided enough information - this depends on the specifics of the object you are creating and what else you're doing with it in the loop. If the object does not create circular references, it should be deallocated on the next iteration. For example, the code ``` for x in range(100000): obj = " " * 10000...
Python garbage collection
1,035,489
23
2009-06-23T21:59:01Z
1,035,526
12
2009-06-23T22:11:24Z
[ "python", "optimization", "memory-management", "garbage-collection" ]
I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?
This is an old error that was corrected for some types in python 2.5. What was happening was that python was not so good at collecting things like empty lists/dictionaries/tupes/floats/ints. In python 2.5 this was fixed...mostly. However floats and ints are singletons for comparisons so once one of those is created it ...
Python garbage collection
1,035,489
23
2009-06-23T21:59:01Z
4,060,791
12
2010-10-30T21:37:29Z
[ "python", "optimization", "memory-management", "garbage-collection" ]
I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?
I think this is circular reference (though the question isn't explicit about this information.) One way to solve this problem is to manually invoke garbage collection. When you manually run garbage collector, it will sweep circular referenced objects too. ``` import gc for i in xrange(10000): j = myObj() pro...
Google App Engine cannot find gdata module
1,035,554
4
2009-06-23T22:19:58Z
1,036,152
9
2009-06-24T02:27:38Z
[ "python", "google-app-engine", "osx", "gdata", "google-data-api" ]
I can run a simple "Hello World" Google App Engine application on localhost with no problems. However, when I add the line "import gdata.auth" to my Python script I get "ImportError: No module named gdata.auth". I have installed the gdata module and added the following line to my .bashrc: ``` export PYTHONPATH=$PYTHO...
Your .bashrc is not known to Google App Engine. Make sure the `gdata` directory (with all its proper contents) is under your application's main directory! See [this article](http://code.google.com/appengine/articles/gdata.html), particularly (and I quote): > To use this library with your Google > App Engine applicati...
Any Python Script to Save Websites Like Firefox?
1,035,825
2
2009-06-23T23:40:19Z
1,035,851
8
2009-06-23T23:47:44Z
[ "python" ]
I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites. Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal.
You could use wget wget -m -k -E [url] ``` -E, --html-extension save HTML documents with `.html' extension. -m, --mirror shortcut for -N -r -l inf --no-remove-listing. -k, --convert-links make links in downloaded HTML point to local files. ```
Recursively convert python object graph to dictionary
1,036,409
16
2009-06-24T04:30:36Z
1,118,038
24
2009-07-13T07:06:27Z
[ "python", "python-2.6" ]
I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again. I found [this question about creating a dictionary from an object's fields](http://stackoverflow.com/questions/61517/python-dictionary...
An amalgamation of my own attempt and clues derived from Anurag Uniyal and Lennart Regebro's answers works best for me: ``` def todict(obj, classkey=None): if isinstance(obj, dict): data = {} for (k, v) in obj.items(): data[k] = todict(v, classkey) return data elif hasattr(o...
Python urllib2 with keep alive
1,037,406
38
2009-06-24T09:50:43Z
1,037,423
28
2009-06-24T09:56:44Z
[ "python", "http", "urllib2", "keep-alive" ]
How can I make a "keep alive" HTTP request using Python's urllib2?
Use the [urlgrabber](http://urlgrabber.baseurl.org/) library. This includes an HTTP handler for urllib2 that supports HTTP 1.1 and keepalive: ``` >>> import urllib2 >>> from urlgrabber.keepalive import HTTPHandler >>> keepalive_handler = HTTPHandler() >>> opener = urllib2.build_opener(keepalive_handler) >>> urllib2.in...
Python urllib2 with keep alive
1,037,406
38
2009-06-24T09:50:43Z
6,163,023
7
2011-05-28T16:54:26Z
[ "python", "http", "urllib2", "keep-alive" ]
How can I make a "keep alive" HTTP request using Python's urllib2?
Or check out [httplib](http://docs.python.org/library/httplib.html)'s HTTPConnection.
Python urllib2 with keep alive
1,037,406
38
2009-06-24T09:50:43Z
8,086,976
11
2011-11-10T22:00:14Z
[ "python", "http", "urllib2", "keep-alive" ]
How can I make a "keep alive" HTTP request using Python's urllib2?
Try [urllib3](https://github.com/shazow/urllib3) which has the following features: * Re-use the same socket connection for multiple requests (HTTPConnectionPool and HTTPSConnectionPool) (with optional client-side certificate verification). * File posting (encode\_multipart\_formdata). * Built-in redirection and retrie...
Are there stack based variables in Python?
1,037,533
5
2009-06-24T10:24:18Z
1,037,542
18
2009-06-24T10:26:42Z
[ "python" ]
If I do this: ``` def foo(): a = SomeObject() ``` Is 'a' destroyed immediately after leaving foo? Or does it wait for some GC to happen?
Yes and no. The object will get destroyed after you leave foo (as long as nothing else has a reference to it), but whether it is immediate or not is an implementation detail, and will vary. In CPython (the standard python implementation), refcounting is used, so the item will immediately be destroyed. There are some e...
Pure python gui library?
1,037,673
5
2009-06-24T10:58:26Z
1,037,722
9
2009-06-24T11:14:16Z
[ "python", "tkinter", "pyqt", "pygtk", "pyobjc" ]
Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries. Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create p...
The path of least effort and best results would be to learn what it takes to deploy an app using those existing GUI libraries.
Pure python gui library?
1,037,673
5
2009-06-24T10:58:26Z
1,037,851
8
2009-06-24T11:45:45Z
[ "python", "tkinter", "pyqt", "pygtk", "pyobjc" ]
Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries. Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create p...
Tkinter is part of the python standard distribution and is installed by default. Expect to find this on all python installs where there is a graphical display in the first place.
Pure python gui library?
1,037,673
5
2009-06-24T10:58:26Z
1,038,494
9
2009-06-24T13:48:15Z
[ "python", "tkinter", "pyqt", "pygtk", "pyobjc" ]
Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries. Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create p...
starting in Python 2.7 and 3.1, Tk will look a lot better. <http://docs.python.org/dev/whatsnew/2.7.html#ttk-themed-widgets-for-tk> "Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk widgets but have a more customizable appearance and can therefore more closely resemble the native platform’s wi...
Data structure for maintaining tabular data in memory?
1,038,160
42
2009-06-24T12:48:51Z
1,038,195
10
2009-06-24T12:58:05Z
[ "python", "data-structures" ]
My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requ...
I personally would use the list of row lists. Because the data for each row is always in the same order, you can easily sort by any of the columns by simply accessing that element in each of the lists. You can also easily count based on a particular column in each list, and make searches as well. It's basically as clos...
Data structure for maintaining tabular data in memory?
1,038,160
42
2009-06-24T12:48:51Z
1,038,203
48
2009-06-24T13:00:00Z
[ "python", "data-structures" ]
My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requ...
Having a "table" in memory that needs lookups, sorting, and arbitrary aggregation really does call out for SQL. You said you tried SQLite, but did you realize that SQLite can use an in-memory-only database? ``` connection = sqlite3.connect(':memory:') ``` Then you can create/drop/query/update tables in memory with al...
Data structure for maintaining tabular data in memory?
1,038,160
42
2009-06-24T12:48:51Z
23,554,199
16
2014-05-08T23:18:39Z
[ "python", "data-structures" ]
My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requ...
A very old question I know but... A pandas DataFrame seems to be the ideal option here. <http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html> From the blurb > Two-dimensional size-mutable, potentially heterogeneous tabular data > structure with labeled axes (rows and columns). Arithm...
In Python, how do I easily generate an image file from some source data?
1,038,550
13
2009-06-24T13:57:05Z
1,038,569
17
2009-06-24T14:00:37Z
[ "python", "image", "data-visualization" ]
I have some some data that I would like to visualize. Each byte of the source data roughly corresponds to a pixel value of the image. What is the easiest way to generate an image file (bitmap?) using Python?
You can create images with a list of pixel values using [Pillow](http://python-pillow.github.io/): ``` from PIL import Image img = Image.new('RGB', (width, height)) img.putdata(my_list) img.save('image.png') ```
How do I remove a substring from the end of a string in Python?
1,038,824
151
2009-06-24T14:44:01Z
1,038,845
222
2009-06-24T14:47:41Z
[ "python", "string" ]
I have the following code: ``` url = 'abcdc.com' print(url.strip('.com')) ``` I expected: `abcdc` I got: `abcd` Now I do ``` url.rsplit('.com', 1) ``` Is there a better way?
You could do this: ``` url = 'abcdc.com' if url.endswith('.com'): url = url[:-4] ``` Or using regular expressions: ``` import re url = 'abcdc.com' url = re.sub('\.com$', '', url) ```
How do I remove a substring from the end of a string in Python?
1,038,824
151
2009-06-24T14:44:01Z
1,038,848
15
2009-06-24T14:48:49Z
[ "python", "string" ]
I have the following code: ``` url = 'abcdc.com' print(url.strip('.com')) ``` I expected: `abcdc` I got: `abcd` Now I do ``` url.rsplit('.com', 1) ``` Is there a better way?
**strip** strips the characters given from both ends of the string, in your case it strips ".", "c", "o" and "m".
How do I remove a substring from the end of a string in Python?
1,038,824
151
2009-06-24T14:44:01Z
1,038,909
12
2009-06-24T14:59:35Z
[ "python", "string" ]
I have the following code: ``` url = 'abcdc.com' print(url.strip('.com')) ``` I expected: `abcdc` I got: `abcd` Now I do ``` url.rsplit('.com', 1) ``` Is there a better way?
Depends on what you know about your url and exactly what you're tryinh to do. If you know that it will always end in '.com' (or '.net' or '.org') then ``` url=url[:-4] ``` is the quickest solution. If it's a more general URLs then you're probably better of looking into the urlparse library that comes with python. I...
How do I remove a substring from the end of a string in Python?
1,038,824
151
2009-06-24T14:44:01Z
1,038,999
24
2009-06-24T15:13:09Z
[ "python", "string" ]
I have the following code: ``` url = 'abcdc.com' print(url.strip('.com')) ``` I expected: `abcdc` I got: `abcd` Now I do ``` url.rsplit('.com', 1) ``` Is there a better way?
``` def strip_end(text, suffix): if not text.endswith(suffix): return text return text[:len(text)-len(suffix)] ```
How do I remove a substring from the end of a string in Python?
1,038,824
151
2009-06-24T14:44:01Z
2,393,022
34
2010-03-06T15:41:45Z
[ "python", "string" ]
I have the following code: ``` url = 'abcdc.com' print(url.strip('.com')) ``` I expected: `abcdc` I got: `abcd` Now I do ``` url.rsplit('.com', 1) ``` Is there a better way?
If you are sure that the string only appears at the end, then the simplest way would be to use 'replace': ``` url = 'abcdc.com' print url.replace('.com','') ```
How do I remove a substring from the end of a string in Python?
1,038,824
151
2009-06-24T14:44:01Z
25,126,098
11
2014-08-04T19:27:22Z
[ "python", "string" ]
I have the following code: ``` url = 'abcdc.com' print(url.strip('.com')) ``` I expected: `abcdc` I got: `abcd` Now I do ``` url.rsplit('.com', 1) ``` Is there a better way?
Since it seems like nobody has pointed this on out yet. ``` url = "www.test.example.com" new_url = url[:url.rfind("."):] ``` This should be more efficient than the methods using split(), as no new list object is created, and this solution works for strings with several dots.
Remove all files in a directory
1,039,711
18
2009-06-24T17:12:19Z
1,039,737
23
2009-06-24T17:19:30Z
[ "python", "unix" ]
Trying to remove all of the files in a certain directory gives me the follwing error: ``` OSError: [Errno 2] No such file or directory: '/home/me/test/*' ``` The code I'm running is: ``` import os test = "/home/me/test/*" os.remove(test) ```
os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory. You can use shutil.rmtree() to do this, however.
Remove all files in a directory
1,039,711
18
2009-06-24T17:12:19Z
1,039,744
7
2009-06-24T17:20:59Z
[ "python", "unix" ]
Trying to remove all of the files in a certain directory gives me the follwing error: ``` OSError: [Errno 2] No such file or directory: '/home/me/test/*' ``` The code I'm running is: ``` import os test = "/home/me/test/*" os.remove(test) ```
Because the \* is a shell construct. Python is literally looking for a file named "\*" in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.
Crunching json with python
1,039,877
9
2009-06-24T17:47:58Z
1,039,897
14
2009-06-24T17:51:22Z
[ "python", "json", "parsing" ]
Echoing my [other question](http://stackoverflow.com/questions/667359/crunching-xml-with-python) now need to find a way to crunch json down to one line: e.g. ``` {"node0":{ "node1":{ "attr0":"foo", "attr1":"foo bar", "attr2":"value with long spaces" } }} ``` would like to...
<http://docs.python.org/library/json.html> ``` >>> import json >>> json.dumps(json.loads(""" ... {"node0":{ ... "node1":{ ... "attr0":"foo", ... "attr1":"foo bar", ... "attr2":"value with long spaces" ... } ... }} ... """)) '{"node0": {"node1": {"attr2": "value with ...
Disable Python return statement from printing object it returns
1,040,285
2
2009-06-24T19:03:18Z
1,040,369
9
2009-06-24T19:16:56Z
[ "python" ]
I want to disable "return" from printing any object it is returning to python shell. e.g A sample python script test.py looks like: ``` def func1(): list = [1,2,3,4,5] print list return list ``` Now, If i do following: ``` python -i test.py >>>func1() ``` This always give me two prints on python shell....
The reason for the print is not the return statement, but the shell itself. The shell does print any object that is a result of an operation on the command line. Thats the reason this happens: ``` >>> a = 'hallo' >>> a 'hallo' ``` The last statement has the value of a as result (since it is not assigned to anything ...
Python "Event" equivalent in Java?
1,040,818
5
2009-06-24T20:32:52Z
1,040,821
7
2009-06-24T20:34:07Z
[ "java", "python", "multithreading" ]
What's the closest thing in Java (perhaps an idiom) to [threading.Event](http://docs.python.org/library/threading.html#event-objects) in Python?
The [`Object.wait()`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait%28%29) [`Object.notify()`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#notify%28%29)/[`Object.notifyAll()`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29). Or [`Condition.await()`](http:...
Pylons is confusing: help!
1,041,471
6
2009-06-24T23:21:22Z
1,041,494
7
2009-06-24T23:32:25Z
[ "python", "pylons" ]
I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it. I've taken a look at Pylons, and I have to say that it's extremely *confusing* to me. All the documentation I can find are just "copy and paste this" tutorials which don't see...
If you're just exploring the wilderness, have a stronger look at Django. It really has nothing to do with CMSs in the traditional sense. You create data models and yes, with a line, you can have an admin panel so you can manage your data. You *can* spin that into a traditional CMS, but that's not what it is by default...
Pylons is confusing: help!
1,041,471
6
2009-06-24T23:21:22Z
1,043,954
9
2009-06-25T13:32:03Z
[ "python", "pylons" ]
I'm a long-time PHP developer looking to try out Python for web development. I've used Python in the past a bit, but I'm still quite new at it. I've taken a look at Pylons, and I have to say that it's extremely *confusing* to me. All the documentation I can find are just "copy and paste this" tutorials which don't see...
Have you looked at the [Pylons book](http://pylonsbook.com/)? I think it does a much better job documenting and explaining how Pylons works. If you are really interested in Pylons, I'd start there.
Get a dict of all variables currently in scope and their values
1,041,639
24
2009-06-25T00:37:23Z
1,041,906
25
2009-06-25T02:28:20Z
[ "python" ]
Consider this snippet: ``` globalVar = 25 def myfunc(paramVar): localVar = 30 print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE) myfunc(123) ``` Where `VARS_IN_SCOPE` is the dict I'm after that would contain `globalVar`, `paramVar` and `localVar`, among other things. I'd like to bas...
Best way to merge two dicts as you're doing (with locals overriding globals) is `dict(globals(), **locals())`. What the approach of merging globals and locals is missing is (a) builtins (I imagine that's deliberate, i.e. you don't think of builtins as "variables"... but, they COULD be, if you so choose!-), and (b) if ...
Get the index of an element in a queryset
1,042,596
17
2009-06-25T07:31:24Z
1,042,651
11
2009-06-25T07:43:46Z
[ "python", "django", "indexing", "django-queryset" ]
I have a QuerySet, let's call it `qs`, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it `obj`. Now I'd like to know at what index `obj` has in `qs`, as *efficiently* as possible. I know that I could use `.index()` from Python or possibly loop through `qs` comp...
QuerySets in Django are actually generators, not lists (for further details, see [Django documentation on QuerySets](http://docs.djangoproject.com/en/dev/ref/models/querysets/#ref-models-querysets)). As such, there is no shortcut to get the index of an element, and I think a plain iteration is the best way to do it. ...
Get the index of an element in a queryset
1,042,596
17
2009-06-25T07:31:24Z
1,042,664
38
2009-06-25T07:50:35Z
[ "python", "django", "indexing", "django-queryset" ]
I have a QuerySet, let's call it `qs`, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it `obj`. Now I'd like to know at what index `obj` has in `qs`, as *efficiently* as possible. I know that I could use `.index()` from Python or possibly loop through `qs` comp...
Compact and probably the most efficient: ``` for index, item in enumerate(your_queryset): ... ```
Get the index of an element in a queryset
1,042,596
17
2009-06-25T07:31:24Z
1,044,552
7
2009-06-25T15:22:17Z
[ "python", "django", "indexing", "django-queryset" ]
I have a QuerySet, let's call it `qs`, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it `obj`. Now I'd like to know at what index `obj` has in `qs`, as *efficiently* as possible. I know that I could use `.index()` from Python or possibly loop through `qs` comp...
Assuming for the purpose of illustration that your models are standard with a primary key `id`, then evaluating ``` list(qs.values_list('id', flat=True)).index(obj.id) ``` will find the index of `obj` in `qs`. While the use of `list` evaluates the queryset, it evaluates not the original queryset but a derived queryse...
Get the index of an element in a queryset
1,042,596
17
2009-06-25T07:31:24Z
14,772,317
14
2013-02-08T12:13:05Z
[ "python", "django", "indexing", "django-queryset" ]
I have a QuerySet, let's call it `qs`, which is ordered by some attribute which is irrelevant to this problem. Then I have an object, let's call it `obj`. Now I'd like to know at what index `obj` has in `qs`, as *efficiently* as possible. I know that I could use `.index()` from Python or possibly loop through `qs` comp...
If you just want to know where you object sits amongst all others (e.g. when determining rank), you can do it quickly by counting the objects before you: ``` index = MyModel.objects.filter(sortField__lt = myObject.sortField).count() ```
can I use expect on windows without installing cygwin?
1,042,778
11
2009-06-25T09:06:01Z
1,042,975
15
2009-06-25T09:52:59Z
[ "python", "ruby", "expect" ]
expect is a module used for spawning child applications and controlling them. I'm interested in python/ruby.
There is [WExpect for Python](http://sage.math.washington.edu/home/goreckc/sage/wexpect/). Notes in the `wexpect.py` file (typos unchanged and highlighting added) > **Wexpect** is a port of pexpext to Windows. Since python for Windows lacks > the requisite modules (pty, tty, select, termios, fctnl, and resource) to r...
Django unit testing with date/time-based objects
1,042,900
19
2009-06-25T09:35:09Z
1,043,119
7
2009-06-25T10:23:35Z
[ "python", "django", "unit-testing", "datetime", "stub" ]
Suppose I have the following `Event` model: ``` from django.db import models import datetime class Event(models.Model): date_start = models.DateField() date_end = models.DateField() def is_over(self): return datetime.date.today() > self.date_end ``` I want to test `Event.is_over()` by creating a...
You could write your own datetime module replacement class, implementing the methods and classes from datetime that you want to replace. For example: ``` import datetime as datetime_orig class DatetimeStub(object): """A datetimestub object to replace methods and classes from the datetime module. Usage:...
Django unit testing with date/time-based objects
1,042,900
19
2009-06-25T09:35:09Z
3,155,865
23
2010-07-01T07:38:18Z
[ "python", "django", "unit-testing", "datetime", "stub" ]
Suppose I have the following `Event` model: ``` from django.db import models import datetime class Event(models.Model): date_start = models.DateField() date_end = models.DateField() def is_over(self): return datetime.date.today() > self.date_end ``` I want to test `Event.is_over()` by creating a...
**EDIT**: Since my answer is the accepted answer here I'm updating it to let everyone know a better way has been created in the meantime, the freezegun library: <https://pypi.python.org/pypi/freezegun>. I use this in all my projects when I want to influence time in tests. Have a look at it. **Original answer:** Repla...
What's the difference between "2*2" and "2**2" in Python?
1,044,854
33
2009-06-25T16:23:16Z
1,044,859
29
2009-06-25T16:24:35Z
[ "python", "syntax" ]
What is the difference between the following codes? **code1**: ``` var=2**2*3 ``` **code2:** ``` var2=2*2*3 ``` I see no difference. This raises the following question. **Why is the code1 used if we can use code2?**
Double stars (`**`) are exponentiation. So "2 times 2" and "2 to the power 2" are the same. Change the numbers and you'll see a difference.
What's the difference between "2*2" and "2**2" in Python?
1,044,854
33
2009-06-25T16:23:16Z
1,044,866
83
2009-06-25T16:25:55Z
[ "python", "syntax" ]
What is the difference between the following codes? **code1**: ``` var=2**2*3 ``` **code2:** ``` var2=2*2*3 ``` I see no difference. This raises the following question. **Why is the code1 used if we can use code2?**
Try: ``` 2**3*2 ``` and ``` 2*3*2 ``` to see the difference. `**` is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2.
What's the difference between "2*2" and "2**2" in Python?
1,044,854
33
2009-06-25T16:23:16Z
1,044,867
11
2009-06-25T16:25:57Z
[ "python", "syntax" ]
What is the difference between the following codes? **code1**: ``` var=2**2*3 ``` **code2:** ``` var2=2*2*3 ``` I see no difference. This raises the following question. **Why is the code1 used if we can use code2?**
``` 2**2 means 2 squared (2^2) 2*2 mean 2 times 2 (2x2) ``` In this case they happen to have the same value, but... ``` 3**3*4 != 3*3*4 ```
How to create Fibonacci Sequence in Java
1,045,151
5
2009-06-25T17:20:15Z
1,045,182
7
2009-06-25T17:23:51Z
[ "java", "python" ]
I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this: ``` a = 0 b = 1 while b < 10: print b a, b = b, b+a ``` The problem is that I can't really make this work i...
I'd do it this way: ``` public class FibonacciAlgorithm { private int a = 0; private int b = 1; public FibonacciAlgorithm() { } public int increment() { int temp = b; b = a + b; a = temp; return value; } public int getValue() { return b; } }...
Is there any good reason to convert an app written in python to c#?
1,045,334
2
2009-06-25T17:59:20Z
1,045,351
13
2009-06-25T18:01:33Z
[ "c#", ".net", "python" ]
I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?
Quote: "If it doesn't break, don't fix it." Unless your company is moving towards .NET and/or there are no more qualified Python developer available anymore, then don't.
Is there any good reason to convert an app written in python to c#?
1,045,334
2
2009-06-25T17:59:20Z
1,045,361
8
2009-06-25T18:03:48Z
[ "c#", ".net", "python" ]
I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?
There's IronPython , a python implementation for .NET. You could port it to that if you really need to get away from the "standard" python vm and onto the .NET platform
How do you create an incremental ID in a Python Class
1,045,344
7
2009-06-25T18:00:22Z
1,045,368
9
2009-06-25T18:04:54Z
[ "python", "class" ]
I would like to create a unique ID for each object I created - here's the class: > ``` > class resource_cl : > def __init__(self, Name, Position, Type, Active): > self.Name = Name > self.Position = Position > self.Type = Type > self.Active = Active > ``` I would like to have a self...
First, use Uppercase Names for Classes. lowercase names for attributes. ``` class Resource( object ): class_counter= 0 def __init__(self, name, position, type, active): self.name = name self.position = position self.type = type self.active = active self.id= Resource.clas...
How do you create an incremental ID in a Python Class
1,045,344
7
2009-06-25T18:00:22Z
1,045,724
25
2009-06-25T19:16:23Z
[ "python", "class" ]
I would like to create a unique ID for each object I created - here's the class: > ``` > class resource_cl : > def __init__(self, Name, Position, Type, Active): > self.Name = Name > self.Position = Position > self.Type = Type > self.Active = Active > ``` I would like to have a self...
Concise and elegant: ``` import itertools class resource_cl(): newid = itertools.count().next def __init__(self): self.id = resource_cl.newid() ... ```