text
stringlengths
185
26.5k
<s>[INST] Getting a list of all subdirectories in the current directory Is there a way to return a list of all the subdirectories in the current directory in Python? I know you can do this with files, but I need to get the list of directories instead. [/INST] Do you mean immediate subdirectories, or every directory right down the tree? Either way, you could use os.walk to do this: os.walk(directory) will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so [x[0] for x in os.walk(directory)] should give you all of the directories. Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much. However, you could use it just to give you the immediate child directories: next(os.walk('.'))[1] Or see the other solutions already posted, using os.listdir and os.path.isdir, including those at "get all of the immediate subdirectories in python". </s>
<s>[INST] Python - Pytz - List of Timezones? I would like to know what are all the possible values for the timezone argument in the Python library Pytz. SOLUTION for tz in pytz.all_timezones: print tz Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare Africa/Johannesburg Africa/Juba Africa/Kampala Africa/Khartoum Africa/Kigali Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda Africa/Lubumbashi Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru Africa/Mbabane Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena Africa/Niamey Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome Africa/Timbuktu Africa/Tripoli Africa/Tunis Africa/Windhoek America/Adak America/Anchorage America/Anguilla America/Antigua America/Araguaina America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Aruba America/Asuncion America/Atikokan America/Atka America/Bahia America/Bahia_Banderas America/Barbados America/Belem America/Belize America/Blanc-Sablon America/Boa_Vista America/Bogota America/Boise America/Buenos_Aires America/Cambridge_Bay America/Campo_Grande America/Cancun America/Caracas America/Catamarca America/Cayenne America/Cayman America/Chicago America/Chihuahua America/Coral_Harbour America/Cordoba America/Costa_Rica America/Creston America/Cuiaba America/Curacao America/Danmarkshavn America/Dawson America/Dawson_Creek America/Denver America/Detroit America/Dominica America/Edmonton America/Eirunepe America/El_Salvador America/Ensenada America/Fort_Wayne America/Fortaleza America/Glace_Bay America/Godthab America/Goose_Bay America/Grand_Turk America/Grenada America/Guadeloupe America/Guatemala America/Guayaquil America/Guyana America/Halifax America/Havana America/Hermosillo America/Indiana/Indianapolis America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Tell_City America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Inuvik America/Iqaluit America/Jamaica America/Jujuy America/Juneau America/Kentucky/Louisville America/Kentucky/Monticello America/Knox_IN America/Kralendijk America/La_Paz America/Lima America/Los_Angeles America/Louisville America/Lower_Princes America/Maceio America/Managua America/Manaus America/Marigot America/Martinique America/Matamoros America/Mazatlan America/Mendoza America/Menominee America/Merida America/Metlakatla America/Mexico_City America/Miquelon America/Moncton America/Monterrey America/Montevideo America/Montreal America/Montserrat America/Nassau America/New_York America/Nipigon America/Nome America/Noronha America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem America/Ojinaga America/Panama America/Pangnirtung America/Paramaribo America/Phoenix America/Port-au-Prince America/Port_of_Spain America/Porto_Acre America/Porto_Velho America/Puerto_Rico America/Rainy_River America/Rankin_Inlet America/Recife America/Regina America/Resolute America/Rio_Branco America/Rosario America/Santa_Isabel America/Santarem America/Santiago America/Santo_Domingo America/Sao_Paulo America/Scoresbysund America/Shiprock America/Sitka America/St_Barthelemy America/St_Johns America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent America/Swift_Current America/Tegucigalpa America/Thule America/Thunder_Bay America/Tijuana America/Toronto America/Tortola America/Vancouver America/Virgin America/Whitehorse America/Winnipeg America/Yakutat America/Yellowknife Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Macquarie Antarctica/Mawson Antarctica/McMurdo Antarctica/Palmer Antarctica/Rothera Antarctica/South_Pole Antarctica/Syowa Antarctica/Vostok Arctic/Longyearbyen Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau Asia/Aqtobe Asia/Ashgabat Asia/Ashkhabad Asia/Baghdad Asia/Bahrain Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei Asia/Calcutta Asia/Choibalsan Asia/Chongqing Asia/Chungking Asia/Colombo Asia/Dacca Asia/Damascus Asia/Dhaka Asia/Dili Asia/Dubai Asia/Dushanbe Asia/Gaza Asia/Harbin Asia/Hebron Asia/Ho_Chi_Minh Asia/Hong_Kong Asia/Hovd Asia/Irkutsk Asia/Istanbul Asia/Jakarta Asia/Jayapura Asia/Jerusalem Asia/Kabul Asia/Kamchatka Asia/Karachi Asia/Kashgar Asia/Kathmandu Asia/Katmandu Asia/Kolkata Asia/Krasnoyarsk Asia/Kuala_Lumpur Asia/Kuching Asia/Kuwait Asia/Macao Asia/Macau Asia/Magadan Asia/Makassar Asia/Manila Asia/Muscat Asia/Nicosia Asia/Novokuznetsk Asia/Novosibirsk Asia/Omsk Asia/Oral Asia/Phnom_Penh Asia/Pontianak Asia/Pyongyang Asia/Qatar Asia/Qyzylorda Asia/Rangoon Asia/Riyadh Asia/Saigon Asia/Sakhalin Asia/Samarkand Asia/Seoul Asia/Shanghai Asia/Singapore Asia/Taipei Asia/Tashkent Asia/Tbilisi Asia/Tehran Asia/Tel_Aviv Asia/Thimbu Asia/Thimphu Asia/Tokyo Asia/Ujung_Pandang Asia/Ulaanbaatar Asia/Ulan_Bator Asia/Urumqi Asia/Vientiane Asia/Vladivostok Asia/Yakutsk Asia/Yekaterinburg Asia/Yerevan Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde Atlantic/Faeroe Atlantic/Faroe Atlantic/Jan_Mayen Atlantic/Madeira Atlantic/Reykjavik Atlantic/South_Georgia Atlantic/St_Helena Atlantic/Stanley Australia/ACT Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Canberra Australia/Currie Australia/Darwin Australia/Eucla Australia/Hobart Australia/LHI Australia/Lindeman Australia/Lord_Howe Australia/Melbourne Australia/NSW Australia/North Australia/Perth Australia/Queensland Australia/South Australia/Sydney Australia/Tasmania Australia/Victoria Australia/West Australia/Yancowinna Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West CET CST6CDT Canada/Atlantic Canada/Central Canada/East-Saskatchewan Canada/Eastern Canada/Mountain Canada/Newfoundland Canada/Pacific Canada/Saskatchewan Canada/Yukon Chile/Continental Chile/EasterIsland Cuba EET EST EST5EDT Egypt Eire Etc/GMT Etc/GMT+0 Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12 Etc/GMT+2 Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7 Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Etc/GMT-10 Etc/GMT-11 Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2 Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6 Etc/GMT-7 Etc/GMT-8 Etc/GMT-9 Etc/GMT0 Etc/Greenwich Etc/UCT Etc/UTC Etc/Universal Etc/Zulu Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Bucharest Europe/Budapest Europe/Chisinau Europe/Copenhagen Europe/Dublin Europe/Gibraltar Europe/Guernsey Europe/Helsinki Europe/Isle_of_Man Europe/Istanbul Europe/Jersey Europe/Kaliningrad Europe/Kiev Europe/Lisbon Europe/Ljubljana Europe/London Europe/Luxembourg Europe/Madrid Europe/Malta Europe/Mariehamn Europe/Minsk Europe/Monaco Europe/Moscow Europe/Nicosia Europe/Oslo Europe/Paris Europe/Podgorica Europe/Prague Europe/Riga Europe/Rome Europe/Samara Europe/San_Marino Europe/Sarajevo Europe/Simferopol Europe/Skopje Europe/Sofia Europe/Stockholm Europe/Tallinn Europe/Tirane Europe/Tiraspol Europe/Uzhgorod Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgograd Europe/Warsaw Europe/Zagreb Europe/Zaporozhye Europe/Zurich GB GB-Eire GMT GMT+0 GMT-0 GMT0 Greenwich HST Hongkong Iceland Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte Indian/Reunion Iran Israel Jamaica Japan Kwajalein Libya MET MST MST7MDT Mexico/BajaNorte Mexico/BajaSur Mexico/General NZ NZ-CHAT Navajo PRC PST8PDT Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Chuuk Pacific/Easter Pacific/Efate Pacific/Enderbury Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti Pacific/Galapagos Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu Pacific/Johnston Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro Pacific/Marquesas Pacific/Midway Pacific/Nauru Pacific/Niue Pacific/Norfolk Pacific/Noumea Pacific/Pago_Pago Pacific/Palau Pacific/Pitcairn Pacific/Pohnpei Pacific/Ponape Pacific/Port_Moresby Pacific/Rarotonga Pacific/Saipan Pacific/Samoa Pacific/Tahiti Pacific/Tarawa Pacific/Tongatapu Pacific/Truk Pacific/Wake Pacific/Wallis Pacific/Yap Poland Portugal ROC ROK Singapore Turkey UCT US/Alaska US/Aleutian US/Arizona US/Central US/East-Indiana US/Eastern US/Hawaii US/Indiana-Starke US/Michigan US/Mountain US/Pacific US/Pacific-New US/Samoa UTC Universal W-SU WET Zulu [/INST] You can list all the available timezones with pytz.all_timezones: In [40]: import pytz In [41]: pytz.all_timezones Out[42]: ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', ...] There is also pytz.common_timezones: In [45]: len(pytz.common_timezones) Out[45]: 403 In [46]: len(pytz.all_timezones) Out[46]: 563 </s>
<s>[INST] Python Time Seconds to h:m:s I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python? [/INST] or you can do >>> import datetime >>> str(datetime.timedelta(seconds=666)) '0:11:06' </s>
<s>[INST] How to manage local vs production settings in Django? What is the recommended way of handling settings for local development and the production server? Some of them (like constants, etc) can be changed/accessed in both, but some of them (like paths to static files) need to remain different, and hence should not be overwritten every time the new code is deployed. Currently, I am adding all constants to settings.py. But every time I change some constant locally, I have to copy it to the production server and edit the file for production specific changes... :( Edit: looks like there is no standard answer to this question, I've accepted the most popular method. [/INST] Two Scoops of Django: Best Practices for Django 1.5 suggests using version control for your settings files and storing the files in a separate directory: project/ app1/ app2/ project/ __init__.py settings/ __init__.py base.py local.py production.py manage.py The base.py file contains common settings (such as MEDIA_ROOT or ADMIN), while local.py and production.py have site-specific settings: In the base file settings/base.py: INSTALLED_APPS = ( # common apps... ) In the local development settings file settings/local.py: from project.settings.base import * DEBUG = True INSTALLED_APPS += ( 'debug_toolbar', # and other apps for local development ) In the file production settings file settings/production.py: from project.settings.base import * DEBUG = False INSTALLED_APPS += ( # other apps for production site ) Then when you run django, you add the --settings option: # Running django for local development $ ./manage.py runserver 0:8000 --settings=project.settings.local # Running django shell on the production site $ ./manage.py shell --settings=project.settings.production The authors of the book have also put up a sample project layout template on Github. </s>
<s>[INST] Relative imports in Python 3 I want to import a function from another file in the same directory. Sometimes it works for me with from .mymodule import myfunction but sometimes I get a SystemError: Parent module '' not loaded, cannot perform relative import Sometimes it works with from mymodule import myfunction, but sometimes I also get a SystemError: Parent module '' not loaded, cannot perform relative import I don't understand the logic here, and I couldn't find any explanation. This looks completely random. Could someone explain to me what's the logic behind all this? [/INST] unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that? It's quite common to have a layout like this... main.py mypackage/ __init__.py mymodule.py myothermodule.py ...with a mymodule.py like this... #!/usr/bin/env python3 # Exported function def as_int(a): return int(a) # Test function for module def _test(): assert as_int('1') == 1 if __name__ == '__main__': _test() ...a myothermodule.py like this... #!/usr/bin/env python3 from .mymodule import as_int # Exported function def add(a, b): return as_int(a) + as_int(b) # Test function for module def _test(): assert add('1', '1') == 2 if __name__ == '__main__': _test() ...and a main.py like this... #!/usr/bin/env python3 from mypackage.myothermodule import add def main(): print(add('1', '1')) if __name__ == '__main__': main() ...which works fine when you run main.py or mypackage/mymodule.py, but fails with mypackage/myothermodule.py, due to the relative import... from .mymodule import as_int The way you're supposed to run it is... python3 -m mypackage.myothermodule ...but it's somewhat verbose, and doesn't mix well with a shebang line like #!/usr/bin/env python3. The simplest fix for this case, assuming the name mymodule is globally unique, would be to avoid using relative imports, and just use... from mymodule import as_int ...although, if it's not unique, or your package structure is more complex, you'll need to include the directory containing your package directory in PYTHONPATH, and do it like this... from mypackage.mymodule import as_int ...or if you want it to work "out of the box", you can frob the PYTHONPATH in code first with this... import sys import os PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from mypackage.mymodule import as_int It's kind of a pain, but there's a clue as to why in an email written by a certain Guido van Rossum... I'm -1 on this and on any other proposed twiddlings of the __main__ machinery. The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern. To make me change my mind you'd have to convince me that it isn't. Whether running scripts inside a package is an antipattern or not is subjective, but personally I find it really useful in a package I have which contains some custom wxPython widgets, so I can run the script for any of the source files to display a wx.Frame containing only that widget for testing purposes. </s>
<s>[INST] How can I improve my paw detection? After my previous question on finding toes within each paw, I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws. You see, my proof of concept basically took the maximal pressure of each sensor over time and would start looking for the sum of each row, until it finds on that != 0.0. Then it does the same for the columns and as soon as it finds more than 2 rows with that are zero again. It stores the minimal and maximal row and column values to some index. As you can see in the figure, this works quite well in most cases. However, there are a lot of downsides to this approach (other than being very primitive): Humans can have 'hollow feet' which means there are several empty rows within the footprint itself. Since I feared this could happen with (large) dogs too, I waited for at least 2 or 3 empty rows before cutting off the paw. This creates a problem if another contact made in a different column before it reaches several empty rows, thus expanding the area. I figure I could compare the columns and see if they exceed a certain value, they must be separate paws. The problem gets worse when the dog is very small or walks at a higher pace. What happens is that the front paw's toes are still making contact, while the hind paw's toes just start to make contact within the same area as the front paw! With my simple script, it won't be able to split these two, because it would have to determine which frames of that area belong to which paw, while currently I would only have to look at the maximal values over all frames. Examples of where it starts going wrong: So now I'm looking for a better way of recognizing and separating the paws (after which I'll get to the problem of deciding which paw it is!). Update: I've been tinkering to get Joe's (awesome!) answer implemented, but I'm having difficulties extracting the actual paw data from my files. The coded_paws shows me all the different paws, when applied to the maximal pressure image (see above). However, the solution goes over each frame (to separate overlapping paws) and sets the four Rectangle attributes, such as coordinates or height/width. I can't figure out how to take these attributes and store them in some variable that I can apply to the measurement data. Since I need to know for each paw, what its location is during which frames and couple this to which paw it is (front/hind, left/right). So how can I use the Rectangles attributes to extract these values for each paw? I have the measurements I used in the question setup in my public Dropbox folder (example 1, example 2, example 3). For anyone interested I also set up a blog to keep you up to date :-) [/INST] If you're just wanting (semi) contiguous regions, there's already an easy implementation in Python: SciPy's ndimage.morphology module. This is a fairly common image morphology operation. Basically, you have 5 steps: def find_paws(data, smooth_radius=5, threshold=0.0001): data = sp.ndimage.uniform_filter(data, smooth_radius) thresh = data > threshold filled = sp.ndimage.morphology.binary_fill_holes(thresh) coded_paws, num_paws = sp.ndimage.label(filled) data_slices = sp.ndimage.find_objects(coded_paws) return object_slices Blur the input data a bit to make sure the paws have a continuous footprint. (It would be more efficient to just use a larger kernel (the structure kwarg to the various scipy.ndimage.morphology functions) but this isn't quite working properly for some reason...) Threshold the array so that you have a boolean array of places where the pressure is over some threshold value (i.e. thresh = data > value) Fill any internal holes, so that you have cleaner regions (filled = sp.ndimage.morphology.binary_fill_holes(thresh)) Find the separate contiguous regions (coded_paws, num_paws = sp.ndimage.label(filled)). This returns an array with the regions coded by number (each region is a contiguous area of a unique integer (1 up to the number of paws) with zeros everywhere else)). Isolate the contiguous regions using data_slices = sp.ndimage.find_objects(coded_paws). This returns a list of tuples of slice objects, so you could get the region of the data for each paw with [data[x] for x in data_slices]. Instead, we'll draw a rectangle based on these slices, which takes slightly more work. The two animations below show your "Overlapping Paws" and "Grouped Paws" example data. This method seems to be working perfectly. (And for whatever it's worth, this runs much more smoothly than the GIF images below on my machine, so the paw detection algorithm is fairly fast...) Here's a full example (now with much more detailed explanations). The vast majority of this is reading the input and making an animation. The actual paw detection is only 5 lines of code. import numpy as np import scipy as sp import scipy.ndimage import matplotlib.pyplot as plt from matplotlib.patches import Rectangle def animate(input_filename): """Detects paws and animates the position and raw data of each frame in the input file""" # With matplotlib, it's much, much faster to just update the properties # of a display object than it is to create a new one, so we'll just update # the data and position of the same objects throughout this animation... infile = paw_file(input_filename) # Since we're making an animation with matplotlib, we need # ion() instead of show()... plt.ion() fig = plt.figure() ax = fig.add_subplot(111) fig.suptitle(input_filename) # Make an image based on the first frame that we'll update later # (The first frame is never actually displayed) im = ax.imshow(infile.next()[1]) # Make 4 rectangles that we can later move to the position of each paw rects = [Rectangle((0,0), 1,1, fc='none', ec='red') for i in range(4)] [ax.add_patch(rect) for rect in rects] title = ax.set_title('Time 0.0 ms') # Process and display each frame for time, frame in infile: paw_slices = find_paws(frame) # Hide any rectangles that might be visible [rect.set_visible(False) for rect in rects] # Set the position and size of a rectangle for each paw and display it for slice, rect in zip(paw_slices, rects): dy, dx = slice rect.set_xy((dx.start, dy.start)) rect.set_width(dx.stop - dx.start + 1) rect.set_height(dy.stop - dy.start + 1) rect.set_visible(True) # Update the image data and title of the plot title.set_text('Time %0.2f ms' % time) im.set_data(frame) im.set_clim([frame.min(), frame.max()]) fig.canvas.draw() def find_paws(data, smooth_radius=5, threshold=0.0001): """Detects and isolates contiguous regions in the input array""" # Blur the input data a bit so the paws have a continous footprint data = sp.ndimage.uniform_filter(data, smooth_radius) # Threshold the blurred data (this needs to be a bit > 0 due to the blur) thresh = data > threshold # Fill any interior holes in the paws to get cleaner regions... filled = sp.ndimage.morphology.binary_fill_holes(thresh) # Label each contiguous paw coded_paws, num_paws = sp.ndimage.label(filled) # Isolate the extent of each paw data_slices = sp.ndimage.find_objects(coded_paws) return data_slices def paw_file(filename): """Returns a iterator that yields the time and data in each frame The infile is an ascii file of timesteps formatted similar to this: Frame 0 (0.00 ms) 0.0 0.0 0.0 0.0 0.0 0.0 Frame 1 (0.53 ms) 0.0 0.0 0.0 0.0 0.0 0.0 ... """ with open(filename) as infile: while True: try: time, data = read_frame(infile) yield time, data except StopIteration: break def read_frame(infile): """Reads a frame from the infile.""" frame_header = infile.next().strip().split() time = float(frame_header[-2][1:]) data = [] while True: line = infile.next().strip().split() if line == []: break data.append(line) return time, np.array(data, dtype=np.float) if __name__ == '__main__': animate('Overlapping paws.bin') animate('Grouped up paws.bin') animate('Normal measurement.bin') Update: As far as identifying which paw is in contact with the sensor at what times, the simplest solution is to just do the same analysis, but use all of the data at once. (i.e. stack the input into a 3D array, and work with it, instead of the individual time frames.) Because SciPy's ndimage functions are meant to work with n-dimensional arrays, we don't have to modify the original paw-finding function at all. # This uses functions (and imports) in the previous code example!! def paw_regions(infile): # Read in and stack all data together into a 3D array data, time = [], [] for t, frame in paw_file(infile): time.append(t) data.append(frame) data = np.dstack(data) time = np.asarray(time) # Find and label the paw impacts data_slices, coded_paws = find_paws(data, smooth_radius=4) # Sort by time of initial paw impact... This way we can determine which # paws are which relative to the first paw with a simple modulo 4. # (Assuming a 4-legged dog, where all 4 paws contacted the sensor) data_slices.sort(key=lambda dat_slice: dat_slice[2].start) # Plot up a simple analysis fig = plt.figure() ax1 = fig.add_subplot(2,1,1) annotate_paw_prints(time, data, data_slices, ax=ax1) ax2 = fig.add_subplot(2,1,2) plot_paw_impacts(time, data_slices, ax=ax2) fig.suptitle(infile) def plot_paw_impacts(time, data_slices, ax=None): if ax is None: ax = plt.gca() # Group impacts by paw... for i, dat_slice in enumerate(data_slices): dx, dy, dt = dat_slice paw = i%4 + 1 # Draw a bar over the time interval where each paw is in contact ax.barh(bottom=paw, width=time[dt].ptp(), height=0.2, left=time[dt].min(), align='center', color='red') ax.set_yticks(range(1, 5)) ax.set_yticklabels(['Paw 1', 'Paw 2', 'Paw 3', 'Paw 4']) ax.set_xlabel('Time (ms) Since Beginning of Experiment') ax.yaxis.grid(True) ax.set_title('Periods of Paw Contact') def annotate_paw_prints(time, data, data_slices, ax=None): if ax is None: ax = plt.gca() # Display all paw impacts (sum over time) ax.imshow(data.sum(axis=2).T) # Annotate each impact with which paw it is # (Relative to the first paw to hit the sensor) x, y = [], [] for i, region in enumerate(data_slices): dx, dy, dz = region # Get x,y center of slice... x0 = 0.5 * (dx.start + dx.stop) y0 = 0.5 * (dy.start + dy.stop) x.append(x0); y.append(y0) # Annotate the paw impacts ax.annotate('Paw %i' % (i%4 +1), (x0, y0), color='red', ha='center', va='bottom') # Plot line connecting paw impacts ax.plot(x,y, '-wo') ax.axis('image') ax.set_title('Order of Steps') </s>
<s>[INST] which day of week given a date python I want to find out the following: given a date (datetime object), what is the corresponding day of the week. For instance Sunday is the first day, Monday: second day.. and so on And then if the input is something like Today's date. The output is maybe 6 (since its Friday) [/INST] Use weekday() (docs): >>> import datetime >>> datetime.datetime.today() datetime.datetime(2012, 3, 23, 23, 24, 55, 173504) >>> datetime.datetime.today().weekday() 4 From the documentation: Return the day of the week as an integer, where Monday is 0 and Sunday is 6. </s>
<s>[INST] Filter dict to contain only certain keys? I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out? [/INST] Constructing a new dict: dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys } Uses dictionary comprehension. If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((your_key, old_dict[your_key]) for ...). It's the same, though uglier. Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict. Removing everything in-place: unwanted = set(keys) - set(your_dict) for unwanted_key in unwanted: del your_dict[unwanted_key] </s>
<s>[INST] if else in a list comprehension I have a list l: l = [22, 13, 45, 50, 98, 69, 43, 44, 1] For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5. I tried [x+1 for x in l if x >= 45 else x+5] But it gives me a syntax error. How can I achieve an if – else like this in a list comprehension? [/INST] >>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1] >>> [x+1 if x >= 45 else x+5 for x in l] [27, 18, 46, 51, 99, 70, 48, 49, 6] Do-something if <condition>, else do-something else. </s>
<s>[INST] matplotlib Legend Markers Only Once I often plot a point on a matplotlib plot with: x = 10 y = 100 plot(x, y, "k*", label="Global Optimum") legend() However, this causes the legend to put a star in the legend twice, such that it looks like: * * Global Optimum when I really want it to look like: * Global Optimum How do I do this? [/INST] This should work: legend(numpoints=1) BTW, if you add the line legend.numpoints : 1 # the number of points in the legend line to your matplotlibrc file, then this will be the new default. [See also scatterpoints, depending on your plot.] API: Link to API docs </s>
<s>[INST] Why is Python's "append" not "push"? Does anyone know why Python's list.append function is not called list.push given that there's already a list.pop that removes and returns the last element (that indexed at -1) and list.append semantic is consistent with that use? [/INST] Because "append" existed long before "pop" was thought of. Python 0.9.1 supported list.append in early 1991. By comparison, here's part of a discussion on comp.lang.python about adding pop in 1997. Guido wrote: To implement a stack, one would need to add a list.pop() primitive (and no, I'm not against this particular one on the basis of any principle). list.push() could be added for symmetry with list.pop() but I'm not a big fan of multiple names for the same operation -- sooner or later you're going to read code that uses the other one, so you need to learn both, which is more cognitive load. You can also see he discusses the idea of if push/pop/put/pull should be at element [0] or after element [-1] where he posts a reference to Icon's list: I stil think that all this is best left out of the list object implementation -- if you need a stack, or a queue, with particular semantics, write a little class that uses a lists In other words, for stacks implemented directly as Python lists, which already supports fast append(), and del list[-1], it makes sense that list.pop() work by default on the last element. Even if other languages do it differently. Implicit here is that most people need to append to a list, but many fewer have occasion to treat lists as stacks, which is why list.append came in so much earlier. </s>
<s>[INST] How to get string objects instead of Unicode ones from JSON in Python? I'm using Python 2 to parse JSON from (ASCII encoded) text files. When loading these files with either json or simplejson, all my string values are cast to Unicode objects instead of string objects. The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them. Is it possible to get string objects instead of Unicode ones from json or simplejson? Here's a small example: >>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode` [/INST] While there are some good answers here, I ended up using PyYAML to parse my JSON files, since it gives the keys and values as str type strings instead of unicode type. Because JSON is a subset of YAML it works nicely: >>> import json >>> import yaml >>> list_org = ['a', 'b'] >>> list_dump = json.dumps(list_org) >>> list_dump '["a", "b"]' >>> json.loads(list_dump) [u'a', u'b'] >>> yaml.safe_load(list_dump) ['a', 'b'] Some things to note though: I get string objects because all my entries are ASCII encoded. If I would use unicode encoded entries, I would get them back as unicode objects — there is no conversion! You should (probably always) use PyYAML's safe_load function; if you use it to load JSON files, you don't need the "additional power" of the load function anyway. If you want a YAML parser that has more support for the 1.2 version of the spec (and correctly parses very low numbers) try Ruamel YAML: pip install ruamel.yaml and import ruamel.yaml as yaml was all I needed in my tests. As stated, there is no conversion! If you can't be sure to only deal with ASCII values (and you can't be sure most of the time), better use a conversion function: I used the one from Mark Amery a couple of times now, it works great and is very easy to use. You can also use a similar function as an object_hook instead, as it might gain you a performance boost on big files. See the slightly more involved answer from Mirec Miskuf for that. </s>
<s>[INST] Python - How do I pass a string into subprocess.Popen (using the stdin argument)? If I do the following: import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] I get: Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles p2cread = stdin.fileno() AttributeError: 'cStringIO.StringI' object has no attribute 'fileno' Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this? [/INST] Popen.communicate() documentation: Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too. Replacing os.popen* pipe = os.popen(cmd, 'w', bufsize) # ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin Warning Use communicate() rather than stdin.write(), stdout.read() or stderr.read() to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. So your example could be written as follows: from subprocess import Popen, PIPE, STDOUT p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0] print(grep_stdout.decode()) # -> four # -> five # -> </s>
<s>[INST] How do I find out my python path using python? How do I find out which directories are listed in my system’s PYTHONPATH variable, from within a Python script (or the interactive shell)? [/INST] You would probably also want this: import sys print(sys.path) Or as a one liner from the terminal: python -c "import sys; print '\n'.join(sys.path)" </s>
<s>[INST] Python dictionary from an object's fields Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields. Thanks [/INST] Note that best practice in current versions of Python is to use new-style classes, i.e. class Foo(object): ... Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary object, it's sufficient to use __dict__. Usually, you'll declare your methods at class level and your attributes at instance level, so __dict__ should be fine. For example: >>> class A(object): ... def __init__(self): ... self.b = 1 ... self.c = 2 ... def do_nothing(self): ... pass ... >>> a = A() >>> a.__dict__ {'c': 2, 'b': 1} Alternatively, depending on what you want to do, it might be nice to inherit from dict. Then your class is already a dictionary, and if you want you can override getattr and/or setattr to call through and set the dict. For example: class Foo(dict): def __init__(self): pass def __getattr__(self, attr): return self[attr] # etc... </s>
<s>[INST] Determine function name from within that function (without using traceback) In Python, without using the traceback module, is there a way to determine a function's name from within that function? Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar's name? Or better yet, foo.bar's name? #foo.py def bar(): print "my name is", __myname__ # <== how do I calculate this at runtime? [/INST] import inspect def foo(): print inspect.stack()[0][3] </s>
<s>[INST] How can I color Python logging output? Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized). Now, Python has the logging module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere. Is there any way to make the Python logging module output in color? What I want (for instance) errors in red, debug messages in blue or yellow, and so on. Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original logging output if color isn't supported. Any ideas how I can get colored output with the logging module? [/INST] I already knew about the color escapes, I used them in my bash prompt a while ago. Thanks anyway. What I wanted was to integrate it with the logging module, which I eventually did after a couple of tries and errors. Here is what I end up with: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) #The background is set with 40 plus the number of the color, and the foreground with 30 #These are the sequences need to get colored ouput RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" def formatter_message(message, use_color = True): if use_color: message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) else: message = message.replace("$RESET", "").replace("$BOLD", "") return message COLORS = { 'WARNING': YELLOW, 'INFO': WHITE, 'DEBUG': BLUE, 'CRITICAL': YELLOW, 'ERROR': RED } class ColoredFormatter(logging.Formatter): def __init__(self, msg, use_color = True): logging.Formatter.__init__(self, msg) self.use_color = use_color def format(self, record): levelname = record.levelname if self.use_color and levelname in COLORS: levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ record.levelname = levelname_color return logging.Formatter.format(self, record) And to use it, create your own Logger: # Custom logger class with multiple destinations class ColoredLogger(logging.Logger): FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)" COLOR_FORMAT = formatter_message(FORMAT, True) def __init__(self, name): logging.Logger.__init__(self, name, logging.DEBUG) color_formatter = ColoredFormatter(self.COLOR_FORMAT) console = logging.StreamHandler() console.setFormatter(color_formatter) self.addHandler(console) return logging.setLoggerClass(ColoredLogger) Just in case anyone else needs it. Be careful if you're using more than one logger or handler: ColoredFormatter is changing the record object, which is passed further to other handlers or propagated to other loggers. If you have configured file loggers etc. you probably don't want to have the colors in the log files. To avoid that, it's probably best to simply create a copy of record with copy.copy() before manipulating the levelname attribute, or to reset the levelname to the previous value, before returning the formatted string (credit to Michael in the comments). </s>
<s>[INST] Split string on whitespace in Python I'm looking for the Python equivalent of String str = "many fancy word \nhello \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex); ["many", "fancy", "word", "hello", "hi"] [/INST] The str.split() method without an argument splits on whitespace: >>> "many fancy word \nhello \thi".split() ['many', 'fancy', 'word', 'hello', 'hi'] </s>
<s>[INST] Get HTML Source of WebElement in Selenium WebDriver using Python I'm using the Python bindings to run Selenium WebDriver. from selenium import webdriver wd = webdriver.Firefox() I know I can grab a webelement like so... elem = wd.find_element_by_css_selector('#my-id') And I know I can get the full page source with... wd.page_source But is there anyway to get the "element source"? elem.source # <-- returns the HTML as a string The selenium webdriver docs for Python are basically non-existent and I don't see anything in the code that seems to enable that functionality. Any thoughts on the best way to access the HTML of an element (and its children)? [/INST] You can read innerHTML attribute to get source of the content of the element or outerHTML for source with the current element. Python: element.get_attribute('innerHTML') Java: elem.getAttribute("innerHTML"); C#: element.GetAttribute("innerHTML"); Ruby: element.attribute("innerHTML") Tested and works with the ChromeDriver. </s>
<s>[INST] Get current time in milliseconds in Python? How can I get the current time in milliseconds in Python? [/INST] For what I needed, here's what I did, based on @samplebias' comment above: import time millis = int(round(time.time() * 1000)) print millis Quick'n'easy. Thanks all, sorry for the brain fart. For reuse: import time current_milli_time = lambda: int(round(time.time() * 1000)) Then: >>> current_milli_time() 1378761833768 </s>
<s>[INST] How can I make sense of the `else` statement in Python loops? Many Python programmers are probably unaware that the syntax of while loops and for loops includes an optional else: clause: for val in iterable: do_something(val) else: clean_up() The body of the else clause is a good place for certain kinds of clean-up actions, and is executed on normal termination of the loop: I.e., exiting the loop with return or break skips the else clause; exiting after a continue executes it. I know this only because I just looked it up (yet again), because I can never remember when the else clause is executed. Always? On "failure" of the loop, as the name suggests? On regular termination? Even if the loop is exited with return? I can never be entirely sure without looking it up. I blame my persisting uncertainty on the choice of keyword: I find else incredibly unmnemonic for this semantics. My question is not "why is this keyword used for this purpose" (which I would probably vote to close, though only after reading the answers and comments), but how can I think about the else keyword so that its semantics make sense, and I can therefore remember it? I'm sure there was a fair amount of discussion about this, and I can imagine that the choice was made for consistency with the try statement's else: clause (which I also have to look up), and with the goal of not adding to the list of Python's reserved words. Perhaps the reasons for choosing else will clarify its function and make it more memorable, but I'm after connecting name to function, not after historical explanation per se. The answers to this question, which my question was briefly closed as a duplicate of, contain a lot of interesting back story. My question has a different focus (how to connect the specific semantics of else with the keyword choice), but I feel there should be a link to this question somewhere. [/INST] (This is inspired by @Mark Tolonen's answer.) An if statement runs its else clause if its condition evaluates to false. Identically, a while loop runs the else clause if its condition evaluates to false. This rule matches the behavior you described: In normal execution, the while loop repeatedly runs until the condition evaluates to false, and therefore naturally exiting the loop runs the else clause. When you execute a break statement, you exit out of the loop without evaluating the condition, so the condition cannot evaluate to false and you never run the else clause. When you execute a continue statement, you evaluate the condition again, and do exactly what you normally would at the beginning of a loop iteration. So, if the condition is true, you keep looping, but if it is false you run the else clause. Other methods of exiting the loop, such as return, do not evaluate the condition and therefore do not run the else clause. for loops behave the same way. Just consider the condition as true if the iterator has more elements, or false otherwise. </s>
<s>[INST] Relationship between scipy and numpy scipy appears to provide most (but not all [1]) of numpy's functions in its own namespace. In other words, if there's a function named numpy.foo, there's almost certainly a scipy.foo. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object. Sometimes, they're different. To give an example that came up recently: numpy.log10 is a ufunc that returns NaNs for negative arguments; scipy.log10 returns complex values for negative arguments, and doesn't appear to be a ufunc. The same can be said about log, log2 and logn, but not about log1p [2]. On the other hand, numpy.exp and scipy.exp appear to be different names for the same ufunc. This is also true of scipy.log1p and numpy.log1p. Another example is numpy.linalg.solve vs scipy.linalg.solve. They're similar, but the latter offers some additional features over the former. Why the apparent duplication? If this is meant to be a wholesale import of numpy into the scipy namespace, why the subtle differences in behaviour and the missing functions? Is there some overarching logic that would help clear up the confusion? [1] numpy.min, numpy.max, numpy.abs and a few others have no counterparts in the scipy namespace. [2] Tested using numpy 1.5.1 and scipy 0.9.0rc2. [/INST] Last time I checked it, the scipy __init__ method executes a from numpy import * so that the whole numpy namespace is included into scipy when the scipy module is imported. The log10 behaviour you are describing is interesting, because both versions are coming from numpy. One is a ufunc, the other is a numpy.lib function. Why scipy is preferring the library function over the ufunc, I don't know off the top of my head. EDIT: In fact, I can answer the log10 question. Looking in the scipy __init__ method I see this: # Import numpy symbols to scipy name space import numpy as _num from numpy import oldnumeric from numpy import * from numpy.random import rand, randn from numpy.fft import fft, ifft from numpy.lib.scimath import * The log10 function you get in scipy comes from numpy.lib.scimath. Looking at that code, it says: """ Wrapper functions to more user-friendly calling of certain math functions whose output data-type is different than the input data-type in certain domains of the input. For example, for functions like log() with branch cuts, the versions in this module provide the mathematically valid answers in the complex plane: >>> import math >>> from numpy.lib import scimath >>> scimath.log(-math.exp(1)) == (1+1j*math.pi) True Similarly, sqrt(), other base logarithms, power() and trig functions are correctly handled. See their respective docstrings for specific examples. """ It seems that module overlays the base numpy ufuncs for sqrt, log, log2, logn, log10, power, arccos, arcsin, and arctanh. That explains the behaviour you are seeing. The underlying design reason why it is done like that is probably buried in a mailing list post somewhere. </s>
<s>[INST] How to split a string into array of characters with Python? I've tried to look around the web for answers to splitting a string into an array of characters but I can't seem to find a simple method str.split(//) does not seem to work like Ruby does. Is there a simple way of doing this without looping? [/INST] >>> s = "foobar" >>> list(s) ['f', 'o', 'o', 'b', 'a', 'r'] You need list </s>
<s>[INST] Dump a NumPy array into a csv file Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format. [/INST] numpy.savetxt saves an array to a text file. import numpy a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ]) numpy.savetxt("foo.csv", a, delimiter=",") </s>
<s>[INST] Change one character in a string in Python? What is the easiest way in Python to replace a character in a string like: text = "abcdefg"; text[1] = "Z"; ^ [/INST] Don't modify strings. Work with them as lists; turn them into strings only when needed. >>> s = list("Hello zorld") >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd'] >>> s[6] = 'W' >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] >>> "".join(s) 'Hello World' Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings. </s>
<s>[INST] Iterating through a range of dates in Python I have the following code to do this, but how can I do it better? Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension. day_count = (end_date - start_date).days + 1 for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]: print strftime("%Y-%m-%d", single_date.timetuple()) Notes I'm not actually using this to print. That's just for demo purposes. The start_date and end_date variables are datetime.date objects because I don't need the timestamps. (They're going to be used to generate a report). Sample Output For a start date of 2009-05-30 and an end date of 2009-06-09: 2009-05-30 2009-05-31 2009-06-01 2009-06-02 2009-06-03 2009-06-04 2009-06-05 2009-06-06 2009-06-07 2009-06-08 2009-06-09 [/INST] Why are there two nested iterations? For me it produces the same list of data with only one iteration: for single_date in (start_date + timedelta(n) for n in range(day_count)): print ... And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary. After all, a linear sequence should only require one iterator, not two. Update after discussion with John Machin: Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates: from datetime import timedelta, date def daterange(start_date, end_date): for n in range(int ((end_date - start_date).days)): yield start_date + timedelta(n) start_date = date(2013, 1, 1) end_date = date(2015, 6, 2) for single_date in daterange(start_date, end_date): print single_date.strftime("%Y-%m-%d") NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range(). </s>
<s>[INST] How to set environment variables in Python I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number. If I do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string. I also want to know how to read the environment variables in python (in the later part of the script) once I set it. [/INST] Environment variables must be strings, so use os.environ["DEBUSSY"] = "1" to set the variable DEBUSSY to the string 1. To access this variable later, simply use print os.environ["DEBUSSY"] Child processes automatically inherit the environment of the parent process -- no special action on your part is required. </s>
<s>[INST] Python String and Integer concatenation I want to create string using integer appended to it, in a for loop. Like this: for i in range [1,10]: string="string"+i But it returns an error: TypeError: unsupported operand type(s) for +: 'int' and 'str' What's the best way to concatenate the String and Integer? [/INST] for i in range (1,10): string="string"+str(i) To get string0, string1 ..... string10, you could do like >>> ["string"+str(i) for i in range(11)] ['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10'] </s>
<s>[INST] How do I update pip itself from inside my virtual environment? I'm able to update pip-managed packages, but how do I update pip itself? According to pip --version, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version. What's the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I've already tried pip update and pip update pip with no success. [/INST] pip is just a PyPI package like any other; you could use it to upgrade itself the same way you would upgrade any package: pip install --upgrade pip On Windows the recommended command is: python -m pip install --upgrade pip </s>
<s>[INST] How can I create a directly-executable cross-platform GUI app using Python? Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please? [/INST] First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: Tkinter - based on Tk GUI toolkit (de-facto standard GUI library for python, free for commercial projects) WxPython - based on WxWidgets (very popular, free for commercial projects) PyQt - based on Qt (also very popular and more stable than WxWidgets but costly license for commercial projects) Complete list is at http://wiki.python.org/moin/GuiProgramming Single executable (Windows) py2exe - Probably the most popular out there (PyInstaller is also gaining in popularity) Single executable (Linux) Freeze - works the same way like py2exe but targets Linux platform Single executable (Mac) py2app - again, works like py2exe but targets Mac OS </s>
<s>[INST] Delete Folder Contents in Python How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see *nix also. [/INST] Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the elif statement. import os, shutil folder = '/path/to/folder' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) #elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print(e) </s>
<s>[INST] Get list from pandas DataFrame column headers I want to get a list of the column headers from a pandas DataFrame. The DataFrame will come from user input so I won't know how many columns there will be or what they will be called. For example, if I'm given a DataFrame like this: >>> my_dataframe y gdp cap 0 1 2 5 1 2 3 9 2 8 7 2 3 3 4 7 4 6 7 7 5 4 8 3 6 8 2 8 7 9 9 10 8 6 6 4 9 10 10 7 I would want to get a list like this: >>> header_list [y, gdp, cap] [/INST] You can get the values as a list by doing: list(my_dataframe.columns.values) </s>
<s>[INST] SSL InsecurePlatform error when using Requests package Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy. I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with Requests I get an InsecurePlatform exception. The error mentions urllib3, but I don't have that installed. I did install it to check if it resolved the error, but it didn't. /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3 /util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest /security.html#insecureplatformwarning. Any ideas as to why I'm getting this? I've checked the docs, as specified in the error message, but the docs are saying to import urllib3 and either disable the warning, or provide a certificate. [/INST] Use the somewhat hidden security feature: pip install 'requests[security]' or pip install pyOpenSSL ndg-httpsclient pyasn1 Both commands install following extra packages: pyOpenSSL ndg-httpsclient pyasn1 Please note that this is not required for python-2.7.9+. If pip install fails with errors, check whether you have required development packages for libffi, libssl and python installed in your system using distribution's package manager: Debian/Ubuntu - python-dev libffi-dev libssl-dev packages. Fedora - openssl-devel python-devel libffi-devel packages. Distro list above is incomplete. Workaround (see the original answer by @TomDotTom): In case you cannot install some of the required development packages, there's also an option to disable that warning: import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() </s>
<s>[INST] Read .mat files in Python Does anyone have successful experience reading binary Matlab .mat files in Python? (I've seen that scipy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed scipy version 0.7.0, and I can't find the loadmat() method) [/INST] Silly me. Forgot to import io... import scipy.io mat = scipy.io.loadmat('file.mat') </s>
<s>[INST] How can I get a list of all classes within current module in Python? I've seen plenty of examples of people extracting all of the classes from a module, usually something like: # foo.py class Foo: pass # test.py import inspect import foo for name, obj in inspect.getmembers(foo): if inspect.isclass(obj): print obj Awesome. But I can't find out how to get all of the classes from the current module. # foo.py import inspect class Foo: pass def print_classes(): for name, obj in inspect.getmembers(???): # what do I do here? if inspect.isclass(obj): print obj # test.py import foo foo.print_classes() This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out? [/INST] Try this: import sys current_module = sys.modules[__name__] In your context: import sys, inspect def print_classes(): for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj): print(obj) And even better: clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass) Because inspect.getmembers() takes a predicate. </s>
<s>[INST] Python try...except comma vs 'as' in except What is the difference between ',' and 'as' in except statements, eg: try: pass except Exception, exception: pass and: try: pass except Exception as exception: pass Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that it is invalid. If they are both valid in 2.6 which should I use? [/INST] The definitive document is PEP-3110: Catching Exceptions Summary: In Python 3.x, using as is required. In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x. In Python 2.5 and earlier, use the comma version, since as isn't supported. </s>
<s>[INST] Search and replace a line in a file in Python I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file [/INST] The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place: import fileinput for line in fileinput.input("test.txt", inplace=True): print "%d: %s" % (fileinput.filelineno(), line), What happens here is: The original file is moved to a backup file The standard output is redirected to the original file within the loop Thus any print statements write back into the original file fileinput has more bells and whistles. For example, it can be used to automatically operate on all files in sys.args[1:], without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a with statement. While fileinput is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable. There are two options: The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back. The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage. </s>
<s>[INST] What is a "callable" in Python? Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means. I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for. Could you give me some explanations, including examples with the magic method ? [/INST] A callable is anything that can be called. The built-in callable (PyCallable_Check in objects.c) checks if the argument is either: an instance of a class with a __call__ method or is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.) The method named __call__ is (according to the documentation) Called when the instance is ''called'' as a function Example class Foo: def __call__(self): print 'called' foo_instance = Foo() foo_instance() #this is calling the __call__ method </s>
<s>[INST] Best way to convert string to bytes in Python 3? There appears to be two different ways to convert a string to bytes, as seen in the answers to TypeError: 'str' does not support the buffer interface Which of these methods would be better or more Pythonic? Or is it just a matter of personal preference? b = bytes(mystring, 'utf-8') b = mystring.encode('utf-8') [/INST] If you look at the docs for bytes, it points you to bytearray: bytearray([source[, encoding[, errors]]]) Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods. The optional source parameter can be used to initialize the array in a few different ways: If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode(). If it is an integer, the array will have that size and will be initialized with null bytes. If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array. If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array. Without an argument, an array of size 0 is created. So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense. For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor. Edit: I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself. Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice. </s>
<s>[INST] Python unittest - opposite of assertRaises? I want to write a test to establish that an Exception is not raised in a given circumstance. It's straightforward to test if an Exception is raised ... sInvalidPath=AlwaysSuppliesAnInvalidPath() self.assertRaises(PathIsNotAValidOne, MyObject, sInvalidPath) ... but how can you do the opposite. Something like this i what I'm after ... sValidPath=AlwaysSuppliesAValidPath() self.assertNotRaises(PathIsNotAValidOne, MyObject, sValidPath) [/INST] try: myFunc() except ExceptionType: self.fail("myFunc() raised ExceptionType unexpectedly!") </s>
<s>[INST] Most pythonic way to delete a file which may not exist I want to delete the file filename if it exists. Is it proper to say if os.path.exists(filename): os.remove(filename) Is there a better way? A one-line way? [/INST] A more pythonic way would be: try: os.remove(filename) except OSError: pass Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists() and follows the python convention of overusing exceptions. It may be worthwhile to write a function to do this for you: import os, errno def silentremove(filename): try: os.remove(filename) except OSError as e: # this would be "except OSError, e:" before Python 2.6 if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory raise # re-raise exception if a different error occured </s>
<s>[INST] How to clear python interpreter console? Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console. I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do. Note: I'm running on Windows, so Ctrl+L doesn't work. [/INST] As you mentioned, you can do a system call: >>> import os >>> clear = lambda: os.system('cls') >>> clear() I am not sure of any other way in Windows. </s>
<s>[INST] How do I keep Python print from adding newlines or spaces? In python, if I say print 'h' I get the letter h and a newline. If I say print 'h', I get the letter h and no newline. If I say print 'h', print 'm', I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator. [/INST] Just a comment. In Python 3, you will use print('h', end='') to suppress the endline terminator, and print('a', 'b', 'c', sep='') to suppress the whitespace separator between items. </s>
<s>[INST] Is there a reason Python strings don't have a string length method? I know that python has a len() function that is used to determine the size of a string, but I was wondering why its not a method of the string object. Update Ok, I realized I was embarrassingly mistaken. __len__() is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see __len__ as the name instead of just len. [/INST] Strings do have a length method: __len__() The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes for you) on objects which are iterable. See Emulating container types for more information. Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment </s>
<s>[INST] Python - The difference between sys.stdout.write and print Are there situations in which sys.stdout.write() is preferable to print? (Examples: better performance; code that makes more sense) [/INST] print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file for example: print >> open('file.txt', 'w'), 'Hello', 'World', 2+3 In Python 3.x, print becomes a function, but it is still possible to pass something else than sys.stdout. See http://docs.python.org/library/functions.html. In Python 2.6+, print is still a statement, but it can be used as a function with from __future__ import print_function Update: There is a little difference between the print function and the print statement (and more generally between a function and a statement) pointed by Bakuriu in comments. In case of error when evaluating arguments: print "something", 1/0, "other" #prints only something because 1/0 raise an Exception print("something", 1/0, "other") #doesn't print anything. The func is not called </s>
<s>[INST] How to change the order of DataFrame columns? I have the following DataFrame (df): import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) I add more column(s) by assignment: df['mean'] = df.mean(1) How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched? [/INST] One easy way would be to reassign the dataframe with a list of the columns, rearranged as needed. This is what you have now: In [6]: df Out[6]: 0 1 2 3 4 mean 0 0.445598 0.173835 0.343415 0.682252 0.582616 0.445543 1 0.881592 0.696942 0.702232 0.696724 0.373551 0.670208 2 0.662527 0.955193 0.131016 0.609548 0.804694 0.632596 3 0.260919 0.783467 0.593433 0.033426 0.512019 0.436653 4 0.131842 0.799367 0.182828 0.683330 0.019485 0.363371 5 0.498784 0.873495 0.383811 0.699289 0.480447 0.587165 6 0.388771 0.395757 0.745237 0.628406 0.784473 0.588529 7 0.147986 0.459451 0.310961 0.706435 0.100914 0.345149 8 0.394947 0.863494 0.585030 0.565944 0.356561 0.553195 9 0.689260 0.865243 0.136481 0.386582 0.730399 0.561593 In [7]: cols = df.columns.tolist() In [8]: cols Out[8]: [0L, 1L, 2L, 3L, 4L, 'mean'] Rearrange cols in any way you want. This is how I moved the last element to the first position: In [12]: cols = cols[-1:] + cols[:-1] In [13]: cols Out[13]: ['mean', 0L, 1L, 2L, 3L, 4L] Then reorder the dataframe like this: In [16]: df = df[cols] # OR df = df.ix[:, cols] In [17]: df Out[17]: mean 0 1 2 3 4 0 0.445543 0.445598 0.173835 0.343415 0.682252 0.582616 1 0.670208 0.881592 0.696942 0.702232 0.696724 0.373551 2 0.632596 0.662527 0.955193 0.131016 0.609548 0.804694 3 0.436653 0.260919 0.783467 0.593433 0.033426 0.512019 4 0.363371 0.131842 0.799367 0.182828 0.683330 0.019485 5 0.587165 0.498784 0.873495 0.383811 0.699289 0.480447 6 0.588529 0.388771 0.395757 0.745237 0.628406 0.784473 7 0.345149 0.147986 0.459451 0.310961 0.706435 0.100914 8 0.553195 0.394947 0.863494 0.585030 0.565944 0.356561 9 0.561593 0.689260 0.865243 0.136481 0.386582 0.730399 </s>
<s>[INST] How can I compare two lists in python and return matches I want to take two lists and find the values that appear in both. a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) would return [5], for instance. [/INST] Not the most efficient one, but by far the most obvious way to do it is: >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) {5} if order is significant you can do it with list comprehensions like this: >>> [i for i, j in zip(a, b) if i == j] [5] (only works for equal-sized lists, which order-significance implies). </s>
<s>[INST] Post JSON using Python Requests I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request". Here is my client code: data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} data_json = simplejson.dumps(data) payload = {'json_payload': data_json} r = requests.post("http://localhost:8080", data=payload) Here is the server code. class Root(object): def __init__(self, content): self.content = content print self.content # this works exposed = True def GET(self): cherrypy.response.headers['Content-Type'] = 'application/json' return simplejson.dumps(self.content) def POST(self): self.content = simplejson.loads(cherrypy.request.body.read()) Any ideas? [/INST] It turns out I was missing the header information. The following works: url = "http://localhost:8080" data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers) </s>
<s>[INST] Select rows from a DataFrame based on values in a column in pandas How to select rows from a DataFrame based on values in some column in pandas? In SQL I would use: select * from table where colume_name = some_value. I tried to look at pandas documentation but did not immediately find the answer. [/INST] To select rows whose column value equals a scalar, some_value, use ==: df.loc[df['column_name'] == some_value] To select rows whose column value is in an iterable, some_values, use isin: df.loc[df['column_name'].isin(some_values)] To select rows whose column value does not equal some_value, use !=: df.loc[df['column_name'] != some_value] isin returns a boolean Series, so to select rows whose value is not in some_values, negate the boolean Series using ~: df.loc[~df['column_name'].isin(some_values)] For example, import pandas as pd import numpy as np df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(), 'B': 'one one two three two two one three'.split(), 'C': np.arange(8), 'D': np.arange(8) * 2}) print(df) # A B C D # 0 foo one 0 0 # 1 bar one 1 2 # 2 foo two 2 4 # 3 bar three 3 6 # 4 foo two 4 8 # 5 bar two 5 10 # 6 foo one 6 12 # 7 foo three 7 14 print(df.loc[df['A'] == 'foo']) yields A B C D 0 foo one 0 0 2 foo two 2 4 4 foo two 4 8 6 foo one 6 12 7 foo three 7 14 If you have multiple values you want to include, put them in a list (or more generally, any iterable) and use isin: print(df.loc[df['B'].isin(['one','three'])]) yields A B C D 0 foo one 0 0 1 bar one 1 2 3 bar three 3 6 6 foo one 6 12 7 foo three 7 14 Note, however, that if you wish to do this many times, it is more efficient to make an index first, and then use df.loc: df = df.set_index(['B']) print(df.loc['one']) yields A C D B one foo 0 0 one bar 1 2 one foo 6 12 or, to include multiple values from the index use df.index.isin: df.loc[df.index.isin(['one','two'])] yields A C D B one foo 0 0 one bar 1 2 two foo 2 4 two foo 4 8 two bar 5 10 one foo 6 12 </s>
<s>[INST] Find all occurrences of a substring in Python Python has string.find() and string.rfind() to get the index of a substring in string. I wonder, maybe there is something like string.find_all() which can return all founded indexes (not only first from beginning or first from end)? For example: string = "test test test test" print string.find('test') # 0 print string.rfind('test') # 15 #that's the goal print string.find_all('test') # [0,5,10,15] [/INST] There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions: >>> [m.start() for m in re.finditer('test', 'test test test test')] [0, 5, 10, 15] If you want to find overlapping matches, lookahead will do that: >>> [m.start() for m in re.finditer('(?=tt)', 'ttt')] [0, 1] If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this: >>> search = 'tt' >>> [m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')] [1] re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you're only iterating through the results once. </s>
<s>[INST] Checking whether a string starts with XXXX I would like to know how to check whether a string starts with "hello" in Python. In Bash I usually do: if [[ "$string" =~ ^hello ]]; then do something here fi How do I achieve the same in Python? [/INST] aString = "hello world" aString.startswith("hello") </s>
<s>[INST] Remove all occurrences of a value from a Python list In Python remove() will remove the first occurrence of value in a list. How to remove all occurrences of a value from a list, without sorting the list? This is what I have in mind. >>> x = [1, 2, 3, 4, 2, 2, 3] >>> def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) >>> remove_values_from_list(x, 2) >>> x [1, 3, 4, 3] [/INST] Functional approach: 2.x >>> x = [1,2,3,2,2,2,3,4] >>> filter(lambda a: a != 2, x) [1, 3, 3, 4] 3.x >>> list(filter((2).__ne__, x)) [1, 3, 3, 4] </s>
<s>[INST] Python and pip, list all versions of a package that's available? Given the name of a Python (2.X) package that can be installed with pip and virtualenv, is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error. I'm trying to install a version for a third party library, but the newest version is too new, there were backwards incompatible changes made. So I'd like to somehow have a list of all the versions that pip knows about, so that I can test them. [/INST] Without actually having to download or install any additional packages you can use the syntax for specifying a particular version while not actually specifying any version, and the available versions will be printed: $ pip install pylibmc== Collecting pylibmc== Could not find a version that satisfies the requirement pylibmc== (from v ersions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6, 0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9, 1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0) No matching distribution found for pylibmc== update: I had changed my answer to have nothing after the ==, this however doesn't work for older versions of pip (those of you should probably update pip) add any string after the == that is not likely to be an install candidate: pip install pylibmc==blork </s>
<s>[INST] Strip HTML from strings in Python from mechanize import Browser br = Browser() br.open('http://somewebpage') html = br.response().readlines() for line in html: print line When printing a line in an HTML file, I'm trying to find a way to only show the contents of each HTML element and not the formatting itself. If it finds '<a href="whatever.com">some text</a>', it will only print 'some text', '<b>hello</b>' prints 'hello', etc. How would one go about doing this? [/INST] I always used this function to strip HTML tags, as it requires only the Python stdlib: On Python 2 from HTMLParser import HTMLParser class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() For Python 3 from html.parser import HTMLParser class MLStripper(HTMLParser): def __init__(self): self.reset() self.strict = False self.convert_charrefs= True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() Note: this works only for 3.1. For 3.2 or above, you need to call the parent class's init function. See Using HTMLParser in Python 3.2 </s>
<s>[INST] Is there any way to do HTTP PUT in python I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST. Is there any way to do an HTTP PUT in python? [/INST] I've used a variety of python HTTP libs in the past, and I've settled on 'Requests' as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like: payload = {'username': 'bob', 'email': 'bob@bob.com'} >>> r = requests.put("http://somedomain.org/endpoint", data=payload) You can then check the response status code with: r.status_code or the response with: r.content Requests has a lot synactic sugar and shortcuts that'll make your life easier. </s>
<s>[INST] Python Dictionary Comprehension Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: l = [] for n in range(1, 11): l.append(n) We can shorten this to a list comprehension: l = [n for n in range(1, 11)]. However, say I want to set a dictionary's keys to the same value. I can do: d = {} for n in range(1, 11): d[n] = True # same value for each I've tried this: d = {} d[i for i in range(1, 11)] = True However, I get a SyntaxError on the for. In addition (I don't need this part, but just wondering), can you set a dictionary's keys to a bunch of different values, like this: d = {} for n in range(1, 11): d[n] = n Is this possible with a dictionary comprehension? d = {} d[i for i in range(1, 11)] = [x for x in range(1, 11)] This also raises a SyntaxError on the for. [/INST] There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like. >>> d = {n: n**2 for n in range(5)} >>> print d {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} If you want to set them all to True: >>> d = {n: True for n in range(5)} >>> print d {0: True, 1: True, 2: True, 3: True, 4: True} What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict. </s>
<s>[INST] Does Python support short-circuiting? Does Python support short-circuiting in boolean expressions? [/INST] Yep, both and and or operators short-circuit -- see the docs. </s>
<s>[INST] How do you round UP a number in Python? This problem is killing me. How does one roundup a number UP in Python? I tried round(number) but it round the number down. Example: round(2.3) = 2.0 and not 3, what I would like The I tried int(number + .5) but it round the number down again! Example: int(2.3 + .5) = 2 Then I tried round(number + .5) but it won't work in edge cases. Example: WAIT! THIS WORKED! Please advise. [/INST] The ceil (ceiling) function: import math print math.ceil(4.2) </s>
<s>[INST] How can I selectively escape percent (%) in Python strings? I have the following code test = "have it break." selectiveEscape = "Print percent % in sentence and not %s" % test print(selectiveEscape) I would like to get the output: Print percent % in sentence and not have it break. What actually happens: selectiveEscape = "Use percent % in sentence and not %s" % test TypeError: %d format: a number is required, not str [/INST] >>> test = "have it break." >>> selectiveEscape = "Print percent %% in sentence and not %s" % test >>> print selectiveEscape Print percent % in sentence and not have it break. </s>
<s>[INST] Passing a dictionary to a function in python as keyword parameters I'd like to call a function in python using a dictionary. Here is some code: d = dict(param='test') def f(param): print param f(d) This prints {'param': 'test'} but I'd like it to just print test. I'd like it to work similarly for more parameters: d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(d) Is this possible? [/INST] Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary So my example becomes: d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(**d) </s>
<s>[INST] Text Progress Bar in the Console Is there a good way to do the following? I wrote a simple console app to upload and download files from an FTP server using the ftplib. Each time some data chunks are downloaded, I want to update a text progress bar, even if it's just a number. But I don't want to erase all the text that's been printed to the console. (Doing a "clear" and then printing the updated percentage.) [/INST] Writing '\r' will move the cursor back to the beginning of the line. This displays a percentage counter: import time import sys for i in range(100): time.sleep(1) sys.stdout.write("\r%d%%" % i) sys.stdout.flush() </s>
<s>[INST] Is it possible to run a Python script as a service in Windows? If possible, how? I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services. Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines. Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? Basically, what is the equivalent of putting a start/stop script in /etc/init.d? [/INST] Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions). This is a basic skeleton for a simple service: import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) Your code would go in the main() method, usually with some kind of infinite loop that might be interrumped by checking a flag, that you set in the SvcStop method </s>
<s>[INST] What is the difference between an expression and a statement in Python? In Python, what is the difference between expressions and statements? [/INST] Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object. Examples: 3 + 5 map(lambda x: x*x, range(10)) [a.x for a in some_iterable] yield 7 Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples: # all the above expressions print 42 if x: do_y() return a = 7 </s>
<s>[INST] Django gives Bad Request (400) when DEBUG = False I am new to django-1.6. When I run the django server with DEBUG = True, it's running perfectly. But when I change DEBUG to False in the settings file, then the server stopped and it gives the following error on the command prompt: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. After I changed ALLOWED_HOSTS to ["http://127.0.0.1:8000",], in the browser I get the error: Bad Request (400) Is it possible to run Django without debug mode? [/INST] The ALLOWED_HOSTS list should contain fully qualified host names, not urls. Leave out the port and the protocol. If you are using 127.0.0.1, I would add localhost to the list too: ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] You could also use * to match any host: ALLOWED_HOSTS = ['*'] Quoting the documentation: Values in this list can be fully qualified names (e.g. 'www.example.com'), in which case they will be matched against the request’s Host header exactly (case-insensitive, not including port). A value beginning with a period can be used as a subdomain wildcard: '.example.com' will match example.com, www.example.com, and any other subdomain of example.com. A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header (perhaps in a middleware; if so this middleware must be listed first in MIDDLEWARE_CLASSES). Bold emphasis mine. The status 400 response you get is due to a SuspiciousOperation exception being raised when your host header doesn't match any values in that list. </s>
<s>[INST] listing all functions in a python module I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python? eg. something like: from somemodule import foo print foo.methods # or whatever is the correct method to call [/INST] You can use dir(module) to see all available methods/attributes. Also check out PyDocs. </s>
<s>[INST] When is del useful in python? I can't really think of any reason why python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign None to it. And when deleting from a dictionary, a del method could be added. Is there any reason to keep del in python, or is it a vestige of Python's pre-garbage collection days? [/INST] Firstly, you can del other things besides local variables del list_item[4] del dictionary["alpha"] Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer. Compare: del foo to foo = None I know in the case of del foo that the intent is to remove the variable from scope. It's not clear that foo = None is doing that. If somebody just assigned foo = None I might think it was dead code. But I instantly know what somebody who codes del foo was trying to do. </s>
<s>[INST] Permanently add a directory to PYTHONPATH Whenever I use sys.path.append, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH? [/INST] If you're using bash (on a Mac or GNU/Linux distro), add this to your ~/.bashrc export PYTHONPATH="${PYTHONPATH}:/my/other/path" </s>
<s>[INST] Seeking clarification on apparent contradictions regarding weakly typed languages I think I understand strong typing, but every time I look for examples for what is weak typing I end up finding examples of programming languages that simply coerce/convert types automatically. For instance, in this article named Typing: Strong vs. Weak, Static vs. Dynamic says that Python is strongly typed because you get an exception if you try to: Python 1 + "1" Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'str' However, such thing is possible in Java and in C#, and we do not consider them weakly typed just for that. Java int a = 10; String b = "b"; String result = a + b; System.out.println(result); C# int a = 10; string b = "b"; string c = a + b; Console.WriteLine(c); In this another article named Weakly Type Languages the author says that Perl is weakly typed simply because I can concatenate a string to a number and viceversa without any explicit conversion. Perl $a=10; $b="a"; $c=$a.$b; print $c; #10a So the same example makes Perl weakly typed, but not Java and C#?. Gee, this is confusing The authors seem to imply that a language that prevents the application of certain operations on values of different types is strongly typed and the contrary means weakly typed. Therefore, at some point I have felt prompted to believe that if a language provides a lot of automatic conversions or coercion between types (as perl) may end up being considered weakly typed, whereas other languages that provide only a few conversions may end up being considered strongly typed. I am inclined to believe, though, that I must be wrong in this interepretation, I just do not know why or how to explain it. So, my questions are: What does it really mean for a language to be truly weakly typed? Could you mention any good examples of weakly typing that are not related to automatic conversion/automatic coercion done by the language? Can a language be weakly typed and strongly typed at the same time? [/INST] UPDATE: This question was the subject of my blog on the 15th of October, 2012. Thanks for the great question! What does it really mean for a language to be "weakly typed"? It means "this language uses a type system that I find distasteful". A "strongly typed" language by contrast is a language with a type system that I find pleasant. The terms are essentially meaningless and you should avoid them. Wikipedia lists eleven different meanings for "strongly typed", several of which are contradictory. This indicates that the odds of confusion being created are high in any conversation involving the term "strongly typed" or "weakly typed". All that you can really say with any certainty is that a "strongly typed" language under discussion has some additional restriction in the type system, either at runtime or compile time, that a "weakly typed" language under discussion lacks. What that restriction might be cannot be determined without further context. Instead of using "strongly typed" and "weakly typed", you should describe in detail what kind of type safety you mean. For example, C# is a statically typed language and a type safe language and a memory safe language, for the most part. C# allows all three of those forms of "strong" typing to be violated. The cast operator violates static typing; it says to the compiler "I know more about the runtime type of this expression than you do". If the developer is wrong, then the runtime will throw an exception in order to protect type safety. If the developer wishes to break type safety or memory safety, they can do so by turning off the type safety system by making an "unsafe" block. In an unsafe block you can use pointer magic to treat an int as a float (violating type safety) or to write to memory you do not own. (Violating memory safety.) C# imposes type restrictions that are checked at both compile-time and at runtime, thereby making it a "strongly typed" language compared to languages that do less compile-time checking or less runtime checking. C# also allows you to in special circumstances do an end-run around those restrictions, making it a "weakly typed" language compared with languages which do not allow you to do such an end-run. Which is it really? It is impossible to say; it depends on the point of view of the speaker and their attitude towards the various language features. </s>
<s>[INST] Web scraping with Python I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available? [/INST] Use urllib2 in combination with the brilliant BeautifulSoup library: import urllib2 from BeautifulSoup import BeautifulSoup # or if you're using BeautifulSoup4: # from bs4 import BeautifulSoup soup = BeautifulSoup(urllib2.urlopen('http://example.com').read()) for row in soup('table', {'class': 'spad'})[0].tbody('tr'): tds = row('td') print tds[0].string, tds[1].string # will print date and sunrise </s>
<s>[INST] How to use Xpath in Python? What is the library? Is there a full implementation? How is the library used? Where is its website? [/INST] libxml2 has a number of advantages: Compliance to the spec Active development and a community participation Speed. This is really a python wrapper around a C implementation. Ubiquity. The libxml2 library is pervasive and thus well tested. Downsides include: Compliance to the spec. It's strict. Things like default namespace handling are easier in other libraries. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic. If you are doing simple path selection, stick with ElementTree ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2. Sample of libxml2 XPath Use import libxml2 doc = libxml2.parseFile("tst.xml") ctxt = doc.xpathNewContext() res = ctxt.xpathEval("//*") if len(res) != 2: print "xpath query: wrong node set size" sys.exit(1) if res[0].name != "doc" or res[1].name != "foo": print "xpath query: wrong node set value" sys.exit(1) doc.freeDoc() ctxt.xpathFreeContext() Sample of ElementTree XPath Use from elementtree.ElementTree import ElementTree mydoc = ElementTree(file='tst.xml') for e in mydoc.findall('/foo/bar'): print e.get('title').text </s>
<s>[INST] Expanding tuples into arguments Is there a way to expand a Python tuple into a function - as actual parameters? For example, here expand() does the magic: tuple = (1, "foo", "bar") def myfun(number, str1, str2): return (number * 2, str1 + str2, str2 + str1) myfun(expand(tuple)) # (2, "foobar", "barfoo") I know one could define myfun as myfun((a, b, c)), but of course there may be legacy code. Thanks [/INST] myfun(*tuple) does exactly what you request. Side issue: don't use as your identifiers builtin type names such as tuple, list, file, set, and so forth -- it's horrible practice and it will come back and byte you when you least expect it, so just get into the habit of actively avoiding hiding builtin names with your own identifiers. </s>
<s>[INST] Is there a short contains function for lists? I see people are using any to gather another list to see if an item exists in a list, but is there a quick way to just do?: if list.contains(myItem): # do something [/INST] You can use this syntax: if myItem in list: # do something Also, inverse operator: if myItem not in list: # do something It's work fine for lists, tuples, sets and dicts (check keys). Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts. </s>
<s>[INST] Finding the average of a list I have to find the average of a list in Python. This is my code so far l = [15, 18, 2, 36, 12, 78, 5, 6, 9] print reduce(lambda x, y: x + y, l) I've got it so it adds together the values in the list, but I don't know how to make it divide into them? [/INST] l = [15, 18, 2, 36, 12, 78, 5, 6, 9] sum(l) / float(len(l)) </s>
<s>[INST] Split a string by spaces -- preserving quoted substrings -- in Python I have a string which is like this: this is "a test" I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ['this','is','a test'] PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen. [/INST] You want split, from the shlex module. >>> import shlex >>> shlex.split('this is "a test"') ['this', 'is', 'a test'] This should do exactly what you want. </s>
<s>[INST] How can I convert a datetime object to milliseconds since epoch (unix time) in Python? I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this? [/INST] It appears to me that the simplest way to do this is import datetime epoch = datetime.datetime.utcfromtimestamp(0) def unix_time_millis(dt): return (dt - epoch).total_seconds() * 1000.0 </s>
<s>[INST] How to change the font size on a matplotlib plot How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot? I know how to change the tick label sizes, this is done with: import matplotlib matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) But how does one change the rest? [/INST] From the matplotlib documentation, font = {'family' : 'normal', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) This sets the font of all items to the font specified by the kwargs object, font. Alternatively, you could also use the rcParams update method as suggested in this answer: matplotlib.rcParams.update({'font.size': 22}) You can find a full list of available properties on the Customizing matplotlib page. </s>
<s>[INST] Check if a given key already exists in a dictionary and increment it Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value? I.e., I want to do this: my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 I.e., I want to increment the value if there's already one there, or set it to 1 otherwise. [/INST] You are looking for collections.defaultdict (available for Python 2.5+). This from collections import defaultdict my_dict = defaultdict(int) my_dict[key] += 1 will do what you want. For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use if key in my_dict: my_dict[key] += 1 else: my_dict[key] = 1 </s>
<s>[INST] Does Python SciPy need BLAS? numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. Which tar do I need to download off this site? I've tried the fortrans, but I keep getting this error (after setting the environment variable obviously). [/INST] If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure. Install linear algebra libraries from repository (for Ubuntu), sudo apt-get install gfortran libopenblas-dev liblapack-dev Then install SciPy, (after downloading the SciPy source): python setup.py install or pip install scipy As the case may be. </s>
<s>[INST] Return None if Dictionary key is not available I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python returns a key_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not exist ? [/INST] You can use get() value = d.get(key) which will return None if key is not in d. You can also provide a different default value that will be returned instead of None: value = d.get(key, "empty") </s>
<s>[INST] How to query as GROUP BY in django? I query a model, Members.objects.all() and it returns say Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop What i want is, to know the best Django way to fire a group_by query to my db, as like, Members.objects.all().group_by('designation') Which doesn't work of course. I know we can do some tricks on "django/db/models/query.py", but i am just curious to know how to do it without patching. [/INST] If you mean to do aggregation and are using Django 1.1 (currently in alpha 1), you can use the new aggregation features of the ORM: from django.db.models import Count Members.objects.values('designation').annotate(dcount=Count('designation')) This results in a query similar to SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation and the output would be of the form [{'designation': 'Salesman', 'dcount': 2}, {'designation': 'Manager', 'dcount': 2}] </s>
<s>[INST] Pandas: change data type of columns I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example: a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] df = pd.DataFrame(a) What is the best way to convert the columns to the appropriate types, in this case columns 2 and 3 into floats? Is there a way to specify the types while converting to DataFrame? Or is it better to create the DataFrame first and then loop through the columns to change the type for each column? Ideally I would like to do this in a dynamic way because there can be hundreds of columns and I don't want to specify exactly which columns are of which type. All I can guarantee is that each columns contains values of the same type. [/INST] How about this? a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] df = pd.DataFrame(a, columns=['one', 'two', 'three']) df Out[16]: one two three 0 a 1.2 4.2 1 b 70 0.03 2 x 5 0 df.dtypes Out[17]: one object two object three object df[['two', 'three']] = df[['two', 'three']].astype(float) df.dtypes Out[19]: one object two float64 three float64 </s>
<s>[INST] How do I get list of methods in a Python class? I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods? Also see: How can I list the methods in a Python 2.5 module? Looping over a Python / IronPython Object Methods Finding the methods an object has How do I look inside a Python object? How Do I Perform Introspection on an Object in Python 2.x? How to get a complete list of object’s methods and attributes? Finding out which functions are available from a class instance in python? [/INST] An example (listing the methods of the optparse.OptionParser class): >>> from optparse import OptionParser >>> import inspect >>> inspect.getmembers(OptionParser, predicate=inspect.ismethod) [([('__init__', <unbound method OptionParser.__init__>), ... ('add_option', <unbound method OptionParser.add_option>), ('add_option_group', <unbound method OptionParser.add_option_group>), ('add_options', <unbound method OptionParser.add_options>), ('check_values', <unbound method OptionParser.check_values>), ('destroy', <unbound method OptionParser.destroy>), ('disable_interspersed_args', <unbound method OptionParser.disable_interspersed_args>), ('enable_interspersed_args', <unbound method OptionParser.enable_interspersed_args>), ('error', <unbound method OptionParser.error>), ('exit', <unbound method OptionParser.exit>), ('expand_prog_name', <unbound method OptionParser.expand_prog_name>), ... ] Notice that getmembers returns a list of 2-tuples. The first item is the name of the member, the second item is the value. You can also pass an instance to getmembers: >>> parser = OptionParser() >>> inspect.getmembers(parser, predicate=inspect.ismethod) ... </s>
<s>[INST] How to use timeit module I understand the concept of what timeit does but I am not sure how to implement it in my code. How can I compare two functions, say insertion_sort and tim_sort, with timeit? [/INST] If you want to use timeit in an interactive Python session, there are two convenient options: Use the IPython shell. It features the convenient %timeit special function: In [1]: def f(x): ...: return x*x ...: In [2]: %timeit for x in range(100): f(x) 100000 loops, best of 3: 20.3 us per loop In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement: >>> def f(x): ... return x * x ... >>> import timeit >>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000) [2.0640320777893066, 2.0876040458679199, 2.0520210266113281] </s>
<s>[INST] How can I convert a character to a integer in Python, and viceversa? I want to get, given a character, its ASCII value. For example, for the character a, I want to get 97, and vice versa. [/INST] Use chr() and ord(): >>> chr(97) 'a' >>> ord('a') 97 </s>
<s>[INST] What is the easiest way to remove all packages installed by pip? I'm trying to fix up one of my virtualenvs - I'd like to reset all of the installed libraries back to the ones that match production. Is there a quick and easy way to do this with pip? [/INST] I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv: pip freeze | xargs pip uninstall -y In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below): pip freeze | grep -v "^-e" | xargs pip uninstall -y </s>
<s>[INST] Python pip install fails: invalid command egg_info I find that recently often when I try to install a Python package using pip, I get the error(s) below. I found a reference online that one has to use "python2 setup.py install" from the download directory, and indeed find that this will then work if I manually find and download the package (from pypi). But, I don't know where pip is downloading packages to, and/or why it is failing in this manner. I tried to do a pip upgrade, but it also failed in a similar manner, with a bunch of "Unknown distribution option" errors (entry_points, zip_safe, test_suite, tests_require)! pip 1.0.1 ActivePython 2.7 Trying to use ActiveState's pypm fails, because they have a smaller library base, and it doesn't include these packages. C:\test>pip install requests-oauth Downloading/unpacking requests-oauth Downloading requests-oauth-0.4.1.tar.gz Running setup.py egg_info for package requests-oauth E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'zip_safe' warnings.warn(msg) E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'egg_info' Complete output from command python setup.py egg_info: E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'zip_safe' warnings.warn(msg) E:\Plang\ActivePython\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'egg_info' [/INST] Install distribute, which comes with egg_info. Should be as simple as pip install Distribute. Distribute has been merged into Setuptools as of version 0.7. If you are using a version <=0.6, upgrade using pip install --upgrade setuptools or easy_install -U setuptools. </s>
<s>[INST] When is "i += x" different from "i = i + x" in Python? I was told that += can have different effects than the standard notation of i = i +. Is there a case in which i += 1 would be different from i = i + 1? [/INST] This depends entirely on the object i. += calls the __iadd__ method (if it exists -- falling back on __add__ if it doesn't exist) whereas + calls the __add__ method1. From an API perspective, __iadd__ is supposed to be used for modifying mutable objects in place (returning the object which was mutated) whereas __add__ should return a new instance of something. For immutable objects, both methods return a new instance, but __iadd__ will put the new instance in the current namespace with the same name that the old instance had. This is why i = 1 i += 1 seems to increment i. In reality, you get a new integer and assign it "on top of" i -- losing one reference to the old integer. In this case, i += 1 is exactly the same as i = i + 1. But, with most mutable objects, it's a different story: As a concrete example: a = [1, 2, 3] b = a b += [1, 2, 3] print a #[1, 2, 3, 1, 2, 3] print b #[1, 2, 3, 1, 2, 3] compared to: a = [1, 2, 3] b = a b = b + [1, 2, 3] print a #[1, 2, 3] print b #[1, 2, 3, 1, 2, 3] notice how in the first example, since b and a reference the same object, when I use += on b, it actually changes b (and a sees that change too -- After all, it's referencing the same list). In the second case however, when I do b = b + [1, 2, 3], this takes the list that b is referencing and concatenates it with a new list [1, 2, 3]. It then stores the concatenated list in the current namespace as b -- With no regard for what b was the line before. 1In the expression x + y, if x.__add__ isn't implemented or if x.__add__(y) returns NotImplemented and x and y have different types, then x + y tries to call y.__radd__(x). So, in the case where you have foo_instance += bar_instance if Foo doesn't implement __add__ or __iadd__ then the result here is the same as foo_instance = bar_instance.__radd__(bar_instance,foo_instance) </s>
<s>[INST] How to read csv into record array in numpy? I wonder if there is a direct way to import the contents of a csv file into a record array, much in the way that R's read.table(), read.delim(), and read.csv() family imports data to R's data frame? Or is the best way to use csv.reader() and then apply something like numpy.core.records.fromrecords()? [/INST] You can use Numpy's genfromtxt() method to do so, by setting the delimiter kwarg to a comma. from numpy import genfromtxt my_data = genfromtxt('my_file.csv', delimiter=',') More information on the function can be found at its respective documentation. </s>
<s>[INST] Why compile Python code? Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something? I also notice that some files in my application get compiled into .pyc while others do not, why is this? [/INST] It's compiled to bytecode which can be used much, much, much faster. The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk. Important addition by Ben Blank: It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster. </s>
<s>[INST] What are the differences between numpy arrays and matrices? Which one should I use? What are the advantages and disadvantages of each? From what I've seen, either one can work as a replacement for the other if need be, so should I bother using both or should I stick to just one of them? Will the style of the program influence my choice? I am doing some machine learning using numpy, so there are indeed lots of matrices, but also lots of vectors (arrays). [/INST] Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays. The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a*b is their matrix product. import numpy as np a=np.mat('4 3; 2 1') b=np.mat('1 2; 3 4') print(a) # [[4 3] # [2 1]] print(b) # [[1 2] # [3 4]] print(a*b) # [[13 20] # [ 5 8]] Both matrix objects and ndarrays have .T to return the transpose, but matrix objects also have .H for the conjugate transpose, and .I for the inverse. In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise. Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise: c=np.array([[4, 3], [2, 1]]) d=np.array([[1, 2], [3, 4]]) print(c*d) # [[4 6] # [6 4]] To obtain the result of matrix multiplication, you use np.dot : print(np.dot(c,d)) # [[13 20] # [ 5 8]] The ** operator also behaves differently: print(a**2) # [[22 15] # [10 7]] print(c**2) # [[16 9] # [ 4 1]] Since a is a matrix, a**2 returns the matrix product a*a. Since c is an ndarray, c**2 returns an ndarray with each component squared element-wise. There are other technical differences between matrix objects and ndarrays (having to do with np.ravel, item selection and sequence behavior). The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations. Writing a program that uses both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect. In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation. If you are willing to give up the visual appeal of numpy matrix product notation, then I think numpy arrays are definitely the way to go. PS. Of course, you really don't have to choose one at the expense of the other, since np.asmatrix and np.asarray allow you to convert one to the other (as long as the array is 2-dimensional). </s>
<s>[INST] Implement touch using Python? touch is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions. How would you implement it as a Python function? Try to be cross platform and complete. (Current Google results for "python touch file" are not that great, but point to os.utime.) [/INST] This tries to be a little more race-free than the other solutions. (The with keyword is new in Python 2.5.) import os def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) Roughly equivalent to this. import os def touch(fname, times=None): fhandle = open(fname, 'a') try: os.utime(fname, times) finally: fhandle.close() Now, to really make it race-free, you need to use futimes and change the timestamp of the open filehandle, instead of opening the file and then changing the timestamp on the filename (which may have been renamed). Unfortunately, Python doesn't seem to provide a way to call futimes without going through ctypes or similar... EDIT As noted by Nate Parsons, Python 3.3 will add specifying a file descriptor (when os.supports_fd) to functions such as os.utime, which will use the futimes syscall instead of the utimes syscall under the hood. In other words: import os def touch(fname, mode=0o666, dir_fd=None, **kwargs): flags = os.O_CREAT | os.O_APPEND with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f: os.utime(f.fileno() if os.utime in os.supports_fd else fname, dir_fd=None if os.supports_fd else dir_fd, **kwargs) </s>
<s>[INST] Turn a string into a valid filename in Python I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python. I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". What's the most elegant solution? The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. [/INST] You can look at the Django framework for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly. Their template/defaultfilters.py (at around line 183) defines a function, slugify, that's probably the gold standard for this kind of thing. Essentially, their code is the following. def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) value = unicode(re.sub('[-\s]+', '-', value)) There's more, but I left it out, since it doesn't address slugification, but escaping. </s>
<s>[INST] How do I set the figure title and axes labels font size in Matplotlib? I am creating a figure in Matplotlib like this: from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title') plt.xlabel('xlabel') plt.ylabel('ylabel') fig.savefig('test.jpg') I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually? [/INST] Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize: from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title', fontsize=20) plt.xlabel('xlabel', fontsize=18) plt.ylabel('ylabel', fontsize=16) fig.savefig('test.jpg') For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page): axes.titlesize : large # fontsize of the axes title axes.labelsize : medium # fontsize of the x any y labels (As far as I can see, there is no way to set x and y label sizes separately.) And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually. </s>
<s>[INST] Finding what methods an object has Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? [/INST] It appears you can use this code, replacing 'object' with the object you're interested in:- [method for method in dir(object) if callable(getattr(object, method))] I discovered it at this site, hopefully that should provide some further detail! </s>
<s>[INST] How do I avoid the "self.x = x; self.y = y; self.z = z" pattern in __init__? I see patterns like def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... quite frequently, often with a lot more parameters. Is there a good way to avoid this type of tedious repetitiveness? Should I inherit from namedtuple? [/INST] EDIT It seems that several people are concerned about presenting this solution, so I will provide a very clear disclaimer. You should not use this solution. I only provide it as information, so you know that the language is capable of this. The rest of the answer is just showing language capabilities, not endorsing using them in this way. ORIGINAL ANSWER There isn't really anything wrong with explicitly copying parameters into attributes. If you have too many parameters in the ctor, it is sometimes considered a code smell and maybe you should group these params into a fewer objects. Other times, it is necessary and there is nothing wrong with it. Anyway, doing it explicitly is the way to go. However, since you are asking HOW it can be done (and not whether it should be done), then one solution is this: class A: def __init__(self, **kwargs): for key in kwargs: setattr(self, key, kwargs[key]) a = A(l=1, d=2) a.l # will return 1 a.d # will return 2 </s>
<s>[INST] Is it a good practice to use try-except-else in Python? From time to time in Python, I see the block: try: try_this(whatever) except SomeException as exception: #Handle exception else: return something What is the reason for the try-except-else to exist? I do not like that kind of programming, as it is using exceptions to perform flow control. However, if it is included in the language, there must be a good reason for it, isn't it? It is my understanding that exceptions are not errors, and that they should only be used for exceptional conditions (e.g. I try to write a file into disk and there is no more space, or maybe I do not have permission), and not for flow control. Normally I handle exceptions as: something = some_default_value try: something = try_this(whatever) except SomeException as exception: #Handle exception finally: return something Or if I really do not want to return anything if an exception happens, then: try: something = try_this(whatever) return something except SomeException as exception: #Handle exception [/INST] "I do not know if it is out of ignorance, but i do not like that kind of programming, as it is using exceptions to perform flow control." In the Python world, using exceptions for flow control is common and normal. Even the Python core developers use exceptions for flow-control and that style is heavily baked into the language (i.e. the iterator protocol uses StopIteration to signal loop termination). In addition, the try-except-style is used to prevent the race-conditions inherent in some of the "look-before-you-leap" constructs. For example, testing os.path.exists results in information that may be out-of-date by the time you use it. Likewise, Queue.full returns information that may be stale. The try-except-else style will produce more reliable code in these cases. "It my understanding that exceptions are not errors, they should only be used for exceptional conditions" In some other languages, that rule reflects their cultural norms as reflected in their libraries. The "rule" is also based in-part on performance considerations for those languages. The Python cultural norm is somewhat different. In many cases, you must use exceptions for control-flow. Also, the use of exceptions in Python does not slow the surrounding code and calling code as it does in some compiled languages (i.e. CPython already implements code for exception checking at every step, regardless of whether you actually use exceptions or not). In other words, your understanding that "exceptions are for the exceptional" is a rule that makes sense in some other languages, but not for Python. "However, if it is included in the language itself, there must be a good reason for it, isn't it?" Besides helping to avoid race-conditions, exceptions are also very useful for pulling error-handling outside loops. This is a necessary optimization in interpreted languages which do not tend to have automatic loop invariant code motion. Also, exceptions can simplify code quite a bit in common situations where the ability to handle an issue is far removed from where the issue arose. For example, it is common to have top level user-interface code calling code for business logic which in turn calls low-level routines. Situations arising in the low-level routines (such as duplicate records for unique keys in database accesses) can only be handled in top-level code (such as asking the user for a new key that doesn't conflict with existing keys). The use of exceptions for this kind of control-flow allows the mid-level routines to completely ignore the issue and be nicely decoupled from that aspect of flow-control. There is a nice blog post on the indispensibility of exceptions here. Also, see this StackOverFlow answer: Are exceptions really for exceptional errors? "What is the reason for the try-except-else to exist?" The else-clause itself is interesting. It runs when there is no exception but before the finally-clause. That is its primary purpose. Without the else-clause, the only option to run additional code before finalization would be the clumsy practice of adding the code to the try-clause. That is clumsy because it risks raising exceptions in code that wasn't intended to be protected by the try-block. The use-case of running additional unprotected code prior to finalization doesn't arise very often. So, don't expect to see many examples in published code. It is somewhat rare. Another use-case for the else-clause is to perform actions that must occur when no exception occurs and that do not occur when exceptions are handled. For example: recip = float('Inf') try: recip = 1 / f(x) except ZeroDivisionError: logging.info('Infinite result') else: logging.info('Finite result') Lastly, the most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation). This use is always optional and isn't strictly necessary. </s>
<s>[INST] Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad? I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil. [/INST] Python (the language) doesn't need a GIL (which is why it can perfectly be implemented on JVM [Jython] and .NET [IronPython], and those implementations multithread freely). CPython (the popular implementation) has always used a GIL for ease of coding (esp. the coding of the garbage collection mechanisms) and of integration of non-thread-safe C-coded libraries (there used to be a ton of those around;-). The Unladen Swallow project, among other ambitious goals, does plan a GIL-free virtual machine for Python -- to quote that site, "In addition, we intend to remove the GIL and fix the state of multithreading in Python. We believe this is possible through the implementation of a more sophisticated GC system, something like IBM's Recycler (Bacon et al, 2001)." </s>
<s>[INST] Python mysqldb: Library not loaded: libmysqlclient.18.dylib I just compiled and installed mysqldb for python 2.7 on my mac os 10.6. I created a simple test file that imports import MySQLdb as mysql Firstly, this command is red underlined and the info tells me "Unresolved import". Then I tried to run the following simple python code import MySQLdb as mysql def main(): conn = mysql.connect( charset="utf8", use_unicode=True, host="localhost",user="root", passwd="",db="" ) if __name__ == '__main__'(): main() When executing it I get the following error message Traceback (most recent call last): File "/path/to/project/Python/src/cvdv/TestMySQLdb.py", line 4, in <module> import MySQLdb as mysql File "build/bdist.macosx-10.6-intel/egg/MySQLdb/__init__.py", line 19, in <module> \namespace cvdv File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 7, in <module> File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dlopen(/Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Users/toom/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_mysql.so Reason: image not found What might be the solution to my problem? EDIT: Actually I found out that the library lies in /usr/local/mysql/lib. So I need to tell my pydev eclipse version where to find it. Where do I set this? [/INST] I solved the problem by creating a symbolic link to the library. I.e. The actual library resides in /usr/local/mysql/lib And then I created a symbolic link in /usr/lib Using the command: sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib so that I have the following mapping: ls -l libmysqlclient.18.dylib lrwxr-xr-x 1 root wheel 44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib That was it. After that everything worked fine. EDIT: Notice, to do this in El Capitan mac os release, you need disable SIP. Here is hint how do it in final release: http://apple.stackexchange.com/a/208481/90910 . </s>
<s>[INST] How to drop rows of Pandas dataframe whose value of certain column is NaN I have a df : >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 600016 4.3 NaN 601009 20111231 601009 NaN NaN 601939 20111231 601939 2.5 NaN 000001 20111231 000001 NaN NaN Then I just want the records whose EPS is not NaN, that is, df.drop(....) will return the dataframe as below: STK_ID EPS cash STK_ID RPT_Date 600016 20111231 600016 4.3 NaN 601939 20111231 601939 2.5 NaN How to do that ? [/INST] This question is already resolved, but... ...also consider the solution suggested by Wouter in his original comment. The ability to handle missing data, including dropna(), is built into pandas explicitly. Aside from potentially improved performance over doing it manually, these functions also come with a variety of options which may be useful. In [24]: df = pd.DataFrame(np.random.randn(10,3)) In [25]: df.ix[::2,0] = np.nan; df.ix[::4,1] = np.nan; df.ix[::3,2] = np.nan; In [26]: df Out[26]: 0 1 2 0 NaN NaN NaN 1 2.677677 -1.466923 -0.750366 2 NaN 0.798002 -0.906038 3 0.672201 0.964789 NaN 4 NaN NaN 0.050742 5 -1.250970 0.030561 -2.678622 6 NaN 1.036043 NaN 7 0.049896 -0.308003 0.823295 8 NaN NaN 0.637482 9 -0.310130 0.078891 NaN In [27]: df.dropna() #drop all rows that have any NaN values Out[27]: 0 1 2 1 2.677677 -1.466923 -0.750366 5 -1.250970 0.030561 -2.678622 7 0.049896 -0.308003 0.823295 In [28]: df.dropna(how='all') #drop only if ALL columns are NaN Out[28]: 0 1 2 1 2.677677 -1.466923 -0.750366 2 NaN 0.798002 -0.906038 3 0.672201 0.964789 NaN 4 NaN NaN 0.050742 5 -1.250970 0.030561 -2.678622 6 NaN 1.036043 NaN 7 0.049896 -0.308003 0.823295 8 NaN NaN 0.637482 9 -0.310130 0.078891 NaN In [29]: df.dropna(thresh=2) #Drop row if it does not have at least two values that are **not** NaN Out[29]: 0 1 2 1 2.677677 -1.466923 -0.750366 2 NaN 0.798002 -0.906038 3 0.672201 0.964789 NaN 5 -1.250970 0.030561 -2.678622 7 0.049896 -0.308003 0.823295 9 -0.310130 0.078891 NaN In [30]: df.dropna(subset=[1]) #Drop only if NaN in specific column (as asked in the question) Out[30]: 0 1 2 1 2.677677 -1.466923 -0.750366 2 NaN 0.798002 -0.906038 3 0.672201 0.964789 NaN 5 -1.250970 0.030561 -2.678622 6 NaN 1.036043 NaN 7 0.049896 -0.308003 0.823295 9 -0.310130 0.078891 NaN There are also other options (See docs at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html), including dropping columns instead of rows. Pretty handy! </s>
<s>[INST] How do I get user IP address in django? How do I get user's IP in django? I have a view like this: # Create your views from django.contrib.gis.utils import GeoIP from django.template import RequestContext from django.shortcuts import render_to_response def home(request): g = GeoIP() client_ip = request.META['REMOTE_ADDR'] lat,long = g.lat_lon(client_ip) return render_to_response('home_page_tmp.html',locals()) But I get this error: KeyError at /mypage/ 'REMOTE_ADDR' Request Method: GET Request URL: http://mywebsite.com/mypage/ Django Version: 1.2.4 Exception Type: KeyError Exception Value: 'REMOTE_ADDR' Exception Location: /mysite/homepage/views.py in home, line 9 Python Executable: /usr/bin/python Python Version: 2.6.6 Python Path: ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6'] Server time: Sun, 2 Jan 2011 20:42:50 -0600 [/INST] def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip Make sure you have reverse proxy (if any) configured correctly (e.g. mod_rpaf installed for Apache). Note: the above uses the first item in X-Forwarded-For, but you might want to use the last item (e.g., in the case of Heroku: Get client's real IP address on Heroku) get_client_ip = lambda req: req.META.get('HTTP_X_FORWARDED_FOR') if req.META.get('HTTP_X_FORWARDED_FOR') else ip = request.META.get('REMOTE_ADDR') And then just pass the request as argument to it; get_client_ip(request) </s>