text
stringlengths
185
26.5k
<s>[INST] Running shell command from Python and capturing the output I want to write a function that will execute a shell command and return its output as a string, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line. What would be a code examp...
<s>[INST] How do I "cd" in Python? cd as in the shell command to change the working directory. How do I change the current working directory in Python? [/INST] You can change the working directory with os.chdir(path) There are two best practices to follow when using this method: Catch the exception (WindowsError, OS...
<s>[INST] Python's equivalent of && in an if statement Here's my code: # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'ab...
<s>[INST] What are the differences between the urllib, urllib2, and requests module? In Python, what are the differences between the urllib, urllib2, and requests module? Why are there three? They seem to do the same thing... [/INST] I know its been said already, but I'd highly recommend the Requests python package: h...
<s>[INST] Is there a simple way to delete a list element by value in python? a=[1,2,3,4] b=a.index(6) del a[b] print a The above shows the following error: Traceback (most recent call last): File "D:\zjm_code\a.py", line 6, in <module> b=a.index(6) ValueError: list.index(x): x not in list So I have to do this: ...
<s>[INST] How to fix "Attempted relative import in non-package" even with __init__.py I'm trying to follow PEP 328, with the following directory structure: pkg/ __init__.py components/ core.py __init__.py tests/ core_test.py __init__.py In core_test.py I have the following import statement from ....
<s>[INST] Python - Split Strings with Multiple Delimiters I think what I want to do is a fairly common task but I've found no reference on the web. I have text, with punctuation, and I want list of the words. "Hey, you - what are you doing here!?" should be ['hey', 'you', 'what', 'are', 'you', 'doing', 'here'] But P...
<s>[INST] Converting unix timestamp string to readable date in Python I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a TypeError: >>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most ...
<s>[INST] Argparse optional positional arguments? I have script which is meant to be used like this: usage: installer.py dir [-h] [-v] dir is a positional argument which is defined like this: parser.add_argument('dir', default=os.getcwd()) I want dir to be optional: when it's not specified it should just be cwd. Unfor...
<s>[INST] Python - time.clock() vs. time.time() - accuracy? Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy? for example: start = time.clock() ... do something elapsed = (time.clock() - start) vs. start = time.time() ... do something elapsed = (time.time() - s...
<s>[INST] JSON datetime between Python and JavaScript I want to send a datetime.datetime object in serialized form from Python using JSON and de-serialize in JavaScript using JSON. What is the best way to do this? [/INST] You can add the 'default' parameter to json.dumps to handle this: date_handler = lambda obj: ( ...
<s>[INST] fatal error: Python.h: No such file or directory I am trying to build a shared library using a C extension file but first I have to generate the output file using the command below: gcc -Wall utilsmodule.c -o Utilc After executing the command, I get this error message: utilsmodule.c:1:20: fatal error: Pytho...
<s>[INST] How can I subtract a day from a Python date? I have a Python datetime.datetime object. What is the best way to subtract one day? [/INST] You can use a timedelta object: from datetime import datetime, timedelta d = datetime.today() - timedelta(days=days_to_subtract) </s>
<s>[INST] Convert date to datetime in Python Silly question, but is there a built-in method for converting a date to a datetime in Python, ie. getting the datetime for the midnight of the date? The opposite conversion is easy - datetime has a .date() method. Do I really have to manually call datetime(d.year, d.month, d...
<s>[INST] List filtering: list comprehension vs. lambda + filter I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items. My code looked like this: my_list = [x for x in my_list if x.attribute == value] But then I thought, wouldn't it be better to wri...
<s>[INST] Converting a String to Dictionary? How can I convert the str representation of a dict, such as the following string, into a dict? s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" I prefer not to use eval. What else can I use? The main reason for this, is one of my coworkers classes he wrote, converts all input int...
<s>[INST] open() in Python does not create a file if it doesn't exist What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw') should do this, right? It is not working for me (Python 2.6.2) and I'm wond...
<s>[INST] Non-blocking read on a subprocess.PIPE in python I'm using the subprocess module to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I in...
<s>[INST] What is the standard Python docstring format? I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style? [/INST] The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guid...
<s>[INST] What is the naming convention in Python for variable and function names? Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() In Python, I have seen the above but ...
<s>[INST] Remove empty strings from a list of strings I want to remove all empty strings from a list of strings in python. My idea looks like this: while '' in str_list: str_list.remove('') Is there any more pythonic way to do this? [/INST] I would use filter: str_list = filter(None, str_list) # fastest str_list ...
<s>[INST] Convert Python dict to object? I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object. For example: >>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} Should be accessible in this way: >>> x = dict2obj(d) >>> x.a 1 >>> x.b.c 2 >>> x.d[1].foo bar I thin...
<s>[INST] Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? For example I have two dicts: Dict A: {'a':1, 'b':2, 'c':3} Dict B: {'b':3, 'c':4, 'd':5} I need a pythonic way of 'combining' two dicts such that the result is : {'a':1, 'b':5, 'c':7, 'd':5} That is to say: if a ke...
<s>[INST] how to detect whether a python variable is a function? I have a variable, x, and I want to know whether it is pointing to a function or not. I had hoped I could do something like: >>> isinstance(x, function) But that gives me: Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name ...
<s>[INST] Build a Basic Python Iterator How would one create an iterative function (or iterator object) in python? [/INST] Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly ca...
<s>[INST] How can I tell if a string repeats itself in Python? I'm looking for a way to test whether or not a given string repeats itself for the entire string or not. Examples: [ '0045662100456621004566210045662100456621', # '00456621' '0072992700729927007299270072992700729927', # '0072...
<s>[INST] Good way to append to a string I want an efficient way to append string to another. Is there any good built-in method to use? [/INST] If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place. The end resul...
<s>[INST] How to print date in a regular format in Python? This is my code: import datetime today = datetime.date.today() print today This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code: import datetime mylist = [] ...
<s>[INST] Use a Glob() to find files recursively in Python? This is what I have: glob(os.path.join('src','*.c')) but I want to search the subfolders of src. Something like this would work: glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src...
<s>[INST] Python's use of __new__ and __init__? I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern. However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is...
<s>[INST] How do I install a Python package with a .whl file? I'm having trouble installing a Python package (specifically, JPype1 0.5.7) on my Windows machine, and would like to install it with Christoph Gohlke's Window binaries. (Which, to my experience, alleviated much of the fuss for many other package installation...
<s>[INST] What is the Python equivalent of static variables inside a function? What is the idiomatic Python equivalent of this C/C++ code? void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } specifically, how does one implement the static member at the function level, as o...
<s>[INST] How to make a class JSON serializable How to make a Python class serializable? A simple class: class FileItem: def __init__(self, fname): self.fname = fname What should I do to be able to get output of: json.dumps() Without an error (FileItem instance at ... is not JSON serializable) [/INST] ...
<s>[INST] How to parse an ISO 8601-formatted date in Python? I need to parse RFC 3339 strings like "2008-09-03T20:56:35.450686Z" into Python's datetime type. I have found strptime in the Python standard library, but it is not very convenient. What is the best way to do this? [/INST] The python-dateutil package can par...
<s>[INST] How do you get the logical xor of two variables in Python? How do you get the logical xor of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string): str1 = raw_input("Enter string one:...
<s>[INST] How to sort a list of objects in Python, based on an attribute of the objects? I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like: >>> ut [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]...
<s>[INST] How to put the legend out of the plot I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced. Kindly help me for the following queries: I want to keep t...
<s>[INST] Traverse a list in reverse order in Python So I can start from len(collection) and end in collection[0]. EDIT: Sorry, I forgot to mention I also want to be able to access the loop index. [/INST] Use the reversed() built-in function: >>> a = ["foo", "bar", "baz"] >>> for i in reversed(a): ... print i ... ...
<s>[INST] How can I use Python to get the system hostname? I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python. [/INST] Use socket and its gethostname() functionality. This will get the hostname of the computer where the Python inter...
<s>[INST] Favorite Django Tips & Features? Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. Please, include only one tip per answer. Add Django version requirements if there are any. [/INST] I'm just going ...
<s>[INST] How to do relative imports in Python? Imagine this directory structure: app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py I'm coding mod1, and I need to import something from mod2. How should I do it? I tried from ..sub2 import mod2 but I'm getting an "At...
<s>[INST] Python try-else What is the intended use of the optional else clause of the try statement? [/INST] The statements in the else block are executed if execution falls off the bottom of the try - if there was no exception. Honestly, I've never found a need. However, Handling Exceptions notes: The use of the els...
<s>[INST] How to get an absolute file path in Python Given a path such as "mydir/myfile.txt", how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with: "C:/example/cwd/mydir/myfile.txt" [/INST] >>> import os >>> os.path.abspath("mydir/myfile.txt") ...
<s>[INST] Proper indentation for Python multiline strings What is the proper indentation for Python multiline strings within a function? def method(): string = """line one line two line three""" or def method(): string = """line one line two line three""" or something else? It ...
<s>[INST] Get Last Day of the Month in Python Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this? [/INST] I didn't notice this earlier when I was looking at the d...
<s>[INST] How to get a function name as a string in Python? In Python, how do I get a function name as a string without calling the function? def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes should output "my_function". Is this available in python? If not, any ...
<s>[INST] Usage of __slots__? What is the purpose of __slots__ in Python — especially with respect to when would I want to use it and when not? [/INST] Quoting Jacob Hallen: The proper use of __slots__ is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytim...
<s>[INST] How to change a string into uppercase I have problem in changing a string into uppercase with Python. In my research, I got string.ascii_uppercase but it doesn't work. The following code: >>s = 'sdsd' >>s.ascii_uppercase Gives this error message: Traceback (most recent call last): File "<console>", line ...
<s>[INST] pg_config executable not found I am having trouble installing psycopg2. I get the following error when I try to pip install psycopg2: Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py b...
<s>[INST] Difference between abstract class and interface in Python What is the difference between abstract class and interface in Python? [/INST] What you'll see sometimes is the following: class Abstract1( object ): """Some description that tells you it's abstract, often listing the methods you're expected t...
<s>[INST] Getting key with maximum value in dictionary? I have a dictionary: keys are strings, values are integers. Example: stats = {'a':1000, 'b':3000, 'c': 100} I'd like to get 'b' as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ...
<s>[INST] How to define two-dimensional array in python I want to define a two-dimensional array without an initialized length like this : Matrix = [][] but it does not work... I've tried the code below, but it is wrong too: Matrix = [5][5] Error: Traceback ... IndexError: list index out of range What is my mistake...
<s>[INST] How to make IPython notebook matplotlib plot inline I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0. I cannot get matplotlib graphics to show up inline. import matplotlib import numpy as np import matplotlib.pyplot as plt %matplotlib inline I have also tried %pylab inline...
<s>[INST] How to check for NaN in python? float('nan') results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it. [/INST] math.isnan() Checks if the float x is a NaN (not a number). NaNs are part of the IEEE 754 standards. Operation like but not limited to inf * 0, in...
<s>[INST] Is there a difference between `==` and `is` in Python? My Google-fu has failed me. In Python, are the following two tests for equality equivalent (ha!)? n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' Does this hold true for objects where you would be comparing instance...
<s>[INST] Django - Set Up A Scheduled Job? I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically. Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentatio...
<s>[INST] if/else in Python's list comprehension? How can I do the following in Python? row = [unicode(x.strip()) for x in row if x is not None else ''] Essentially: replace all the Nones with empty strings, and then carry out a function. [/INST] You can totally do that, it's just an ordering issue: [ unicode(x.str...
<s>[INST] Creating a singleton in Python This question is not for the discussion of whether or not the singleton design pattern is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most pythonic. In this instance I define 'most ...
<s>[INST] How to detect a Christmas Tree? Which image processing techniques could be used to implement an application that detects the christmas trees displayed in the following images? I'm searching for solutions that are going to work on all these images. Therefore, approaches that require training haar cascade...
<s>[INST] How to get the filename without the extension from a path in Python? How to get the filename without the extension from a path in Python? I found out a method called os.path.basename to get the filename with extension. But even when I import os, I am not able to call it path.basename. Is it possible to call i...
<s>[INST] Python remove all whitespace in a string I want to eliminate all the whitespace from a string, on both ends, and in between words. I have this Python code: def my_handle(self): sentence = ' hello apple ' sentence.strip() But that only eliminates the whitespace on both sides of the string. How do I ...
<s>[INST] How to get time of a python program execution? I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running. I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program. [/INST] The sim...
<s>[INST] Best practice for Python Assert Is there a performance or code maintenance issue with using assert as part of the standard code instead of using it just for debugging purposes? Is assert x >= 0, 'x is less than zero' better or worse than if x < 0: raise Exception, 'x is less than zero' Also, is there ...
<s>[INST] How to print number with commas as thousands separators? I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number 1234567 as 1,234,567. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest pra...
<s>[INST] Shuffling a list of objects in python I have a list of objects in Python and I want to shuffle them. I thought I could use the random.shuffle method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this? import random class a: foo = "bar" ...
<s>[INST] Finding local IP addresses using Python's stdlib How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? [/INST] I just found this but it seems a bit hackish, however they say tried it on *nix and I did on windows and it worked. i...
<s>[INST] What are the differences between json and simplejson Python modules? I have seen many projects using simplejson module instead of json module from the Standard Library. Also, there are many different simplejson modules. Why would use these alternatives, instead of the one in the Standard Library? [/INST] jso...
<s>[INST] Importing files from different folder in Python I have the following folder structure. application/app/folder/file.py and I want to import some functions from file.py in another Python file which resides in application/app2/some_folder/some_file.py I've tried from application.app.folder.file import func_name ...
<s>[INST] How do I write JSON data to a file in Python? I have JSON data stored in the variable data. I want to write this to a text file for testing so I don't have to grab the data from the server each time. Currently, I am trying this: obj = open('data.txt', 'wb') obj.write(data) obj.close And am receiving the erro...
<s>[INST] How do I capture SIGINT in Python? I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C signal, and I'd like to do some cleanup. In Perl I'd do this: $SIG{'INT'} = 'exit_gracefully'; sub exit_gracefully { print "...
<s>[INST] Running unittest with typical test directory structure The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own test directory: new_project/ antigravity/ antigravity.py test/ test_antigravity.py setup.py etc. for...
<s>[INST] Where do the Python unit tests go? If you're writing a library, or an app, where do the unit test files go? It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules...
<s>[INST] Python Create unix timestamp five minutes in the future I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch...
<s>[INST] How do you test that a Python function throws an exception? How does one write a unittest that fails only if a function doesn't throw an expected exception? [/INST] Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example: import mymod class MyTestCase(unittest.TestCase...
<s>[INST] Disable output buffering Is output buffering enabled by default in Python's interpreter for sys.stdout? If the answer is positive, what are all the ways to disable it? Suggestions so far: Use the -u command line switch Wrap sys.stdout in an object that flushes after every write Set PYTHONUNBUFFERED env var s...
<s>[INST] What is setup.py? Can anyone please explain, what is setup.py and how can it be configured or used? [/INST] setup.py is a python file, which usually tells you that the module/package you are about to install have been packaged and distributed with Distutils, which is the standard for distributing Python Modu...
<s>[INST] How to print the full traceback without halting the program? I'm writing a program that parses 10 websites, locates data files, saves the files, and then parses them to make data that can be readily used in the NumPy library. There are tons of errors this file encounters through bad links, poorly formed XML, ...
<s>[INST] How can I open multiple files using "with open" in Python? I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with statement: try: with open('a', 'w') as a and open('b', 'w') as b: do_something() except ...
<s>[INST] Python decimal range() step value Is there a way to step between 0 and 1 by 0.1? I thought I could do it like the following, but it failed: for i in range(0, 1, 0.1): print i Instead, it says that the step argument cannot be zero, which I did not expect. [/INST] You can also use the NumPy library (whic...
<s>[INST] Best way to strip punctuation from a string in Python It seems like there should be a simpler way than: import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) Is there? [/INST] From an efficiency perspective, you're not going to beat tr...
<s>[INST] Iterating over a string In C++, I could do: for (int i = 0; i < str.length(); ++i) std::cout << str[i] << std::endl; How do I iterate over a string in Python? [/INST] As Johannes pointed out, for c in "string": #do something with c You can iterate pretty much anything in python using the for loop ...
<s>[INST] Dynamic module import in Python I'm writing a Python application that takes as a command as an argument, for example: $ python myapp.py command1 I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. Th...
<s>[INST] What is a Python egg? I'm new to Python and am just trying to understand how its packages work. Presumably "eggs" are some sort of packaging mechanism, but what would be a quick overview of what role they play and maybe some information on why they're useful and how to create them? [/INST] Same concept as a...
<s>[INST] How to get full path of current file's directory in Python? I want to get the current file's directory path. I tried: >>> os.path.abspath(__file__) 'C:\\python27\\test.py' But how can I retrieve the directory's path? For example: 'C:\\python27\\' [/INST] If you mean the directory of the script being run: ...
<s>[INST] Multiprocessing vs Threading Python I am trying to understand the advantages of multiprocessing over threading. I know that multiprocessing gets around the Global Interpreter Lock, but what other advantages are there, and can threading not do the same thing? [/INST] Here are some pros/cons I came up with. Mu...
<s>[INST] What is the use of "assert" in Python? I have been reading some source code and in several places I have seen the usage of assert. What does it mean exactly? What is its usage? [/INST] The assert statement exists in almost every programming language. When you do... assert condition ... you're telling the p...
<s>[INST] Does Python have “private” variables in classes? I'm coming from the Java world and reading Bruce Eckels' Python 3 Patterns, Recipes and Idioms. While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, th...
<s>[INST] What is a "slug" in Django? When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? (I have read its definition in this glossary.) [/INST] It's a way of gener...
<s>[INST] How can I iterate through two lists in parallel in Python? I have two iterables in Python, and I want to go over them in pairs: foo = (1, 2, 3) bar = (4, 5, 6) for (f, b) in some_iterator(foo, bar): print "f: ", f, "; b: ", b It should result in: f: 1; b: 4 f: 2; b: 5 f: 3; b: 6 One way to do it is to ...
<s>[INST] How do I remove the first Item from a Python list? Possible Duplicate: good primer for python slice notation I have the list [0, 1, 2, 3, 4] I'd like to make it into [1, 2, 3, 4]. How do I go about this? [/INST] Python List list.pop(index) >>> l = [0, 1, 2, 3, 4] >>> l.pop(0) 0 >>> l [1, 2, 3, 4] del li...
<s>[INST] Python - Intersection of two lists I know how to get an intersection of two flat lists: b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2] or def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2) But when I have to find intersection for nested lists the...
<s>[INST] Call a parent class's method from child class in Python? When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: package Foo; sub frotz { return "B...
<s>[INST] How do I determine the size of an object in Python? In C, we can find the size of an int, char, etc. I want to know how to get size of objects like a string, integer, etc. in Python. Related question: How many bytes per element are there in a Python list (tuple)? I am using an XML file which contains size fie...
<s>[INST] How to generate all permutations of a list in Python How do you generate all the permutations of a list in Python, independently of the type of elements in that list? For example: permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1,...
<s>[INST] How do I convert datetime to date (in Python)? How do I convert a datetime.datetime object (for example, the return value of datetime.datetime.now()) to a datetime.date object in Python? [/INST] Use the date() method: datetime.datetime.now().date() </s>
<s>[INST] How to check what OS am I running on in Python? What do I need to look at to see if I'm on Windows, Unix, etc? [/INST] >>> import os >>> print os.name posix >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' See: platform — Access to underlying platform’s identi...
<s>[INST] Calling C/C++ from python? What would be the quickest way to construct a python binding to a C or C++ library? (using windows if this matters) [/INST] I like ctypes a lot, swig always tended to give me problems. Also ctypes has the advantage that you don't need to satisfy any compile time dependency on pytho...
<s>[INST] What is the common header format of Python files? I came across the following header format for Python source files in a document about Python coding guidelines: #!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet...
<s>[INST] Python style: multiple-line conditions in IFs Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something Isn't very very appealing visually, because the action blen...
<s>[INST] How do I do a case insensitive string comparison in Python? What's the best way to do case insensitive string comparison in Python? I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values i...