title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
5,877,368
222
2011-05-04T00:56:29Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
Similar to [Harley's answer](http://stackoverflow.com/questions/415511/how-to-get-current-time-in-python/415519#415519), but use the `str()` function for a quick-n-dirty, slightly more human readable format: ``` >>> from datetime import datetime >>> str(datetime.now()) '2011-05-03 17:45:35.177000' ```
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
14,229,023
175
2013-01-09T05:50:34Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
``` >>> from datetime import datetime >>> datetime.now().strftime('%Y-%m-%d %H:%M:%S') ``` For this example, the output will be like this: `'2013-09-18 11:16:32'` The format for `strftime` is at: <https://docs.python.org/2/library/time.html#time.strftime>
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
17,287,377
16
2013-06-25T00:38:25Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
I'll contribute to this because `.isoformat()` is in the documentation but not yet here (this is mighty similar to @Ray Vega's answer): ``` >>>import datetime >>> datetime.datetime.now().isoformat() '2013-06-24T20:35:55.982000' ```
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
18,980,227
13
2013-09-24T11:21:10Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
Quickest way is ``` >>> import time >>> time.strftime("%Y%m%d") '20130924' ```
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
19,710,846
27
2013-10-31T15:39:39Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
All good suggestions, but I find it easiest to use `ctime()` myself: ``` In [2]: from time import ctime In [3]: ctime() Out[3]: 'Thu Oct 31 11:40:53 2013' ``` This gives a nicely formatted string representation of current local time.
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
27,611,645
8
2014-12-22T22:52:47Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
`datetime.now()` returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions ("fall back"). To avoid ambiguity either UTC timezone should be used: ``` from datetime import datetime utc_time = datetime.utcnow() print(utc_time)...
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
27,866,830
11
2015-01-09T18:24:49Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
This is what I ended up going with: ``` >>>from time import strftime >>>strftime("%m/%d/%Y %H:%M") 01/09/2015 13:11 ``` Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation [here](https://docs.pytho...
How to get current time in Python
415,511
1,153
2009-01-06T04:54:23Z
28,576,383
38
2015-02-18T05:08:34Z
[ "python", "datetime", "time" ]
What is the module/method used to get current time?
> # How do I get the current time in Python? ## The `time` module The `time` module provides functions that tells us the time in "seconds since the epoch" as well as other utilities. ``` import time ``` ### Unix Epoch Time This is the format you should get timestamps in for saving in databases. It is a simple floa...
What does the “|” sign mean in Python?
417,396
7
2009-01-06T17:18:20Z
417,438
16
2009-01-06T17:28:40Z
[ "python", "syntax-rules" ]
[This question](http://stackoverflow.com/questions/417265/what-does-sign-mean-in-django) originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve.
In Python, the `'|'` operator is defined by default on integer types and set types. If the two operands are integers, then it will perform a [bitwise or](http://en.wikipedia.org/wiki/Bitwise_operation#OR), which is a mathematical operation. If the two operands are `set` types, the `'|'` operator will return the union...
How can I use Numerical Python with Python 2.6
417,664
2
2009-01-06T18:41:29Z
417,674
9
2009-01-06T18:45:16Z
[ "python", "windows", "numpy" ]
I'm forced to upgrade to Python 2.6 and am having issues using Numerical Python ([NumPy](http://en.wikipedia.org/wiki/NumPy)) with Python 2.6 in Windows. I'm getting the following error... ``` Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from numpy.core.numeric import array,dot,all ...
How did you install it? NumPy doesn't currently have a Python 2.6 binary. If you have [LAPACK](http://en.wikipedia.org/wiki/LAPACK)/[ATLAS](http://en.wikipedia.org/wiki/Automatically_Tuned_Linear_Algebra_Software)/[BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms), etc. and a development environment...
Why does Python's string.printable contains unprintable characters?
418,176
12
2009-01-06T21:10:31Z
418,200
25
2009-01-06T21:15:36Z
[ "python", "character-encoding" ]
I have two String.printable mysteries in the one question. First, in Python 2.6: ``` >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' ``` Look at the end of the string, and you'll find '\x0b\x0c' sticking out like a sore-thumb. Why...
There is a difference in "printable" for "can be displayed on your screen". Your terminal displays the low ascii printer control codes 0x0B and 0x0C as the male and female symbols because that is what those indices in your font contain. Those characters are more accurately described as the Vertical Tabulator and Form F...
How to convert XML to objects?
418,497
19
2009-01-06T22:47:14Z
418,728
7
2009-01-07T00:15:27Z
[ "python", "xml" ]
I need to load an XML file and put the contents into an object-oriented structure. I want to take this: ``` <main> <object1 attr="name">content</object> </main> ``` and turn it into something like this: ``` main main.object1 = "content" main.object1.attr = "name" ``` It'll have a more complicated structure than...
I've been recommending this more than once today, but try [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) (easy\_install BeautifulSoup). ``` from BeautifulSoup import BeautifulSoup xml = """ <main> <object attr="name">content</object> </main> """ soup = BeautifulSoup(xml) # look in the main node ...
How to convert XML to objects?
418,497
19
2009-01-06T22:47:14Z
419,232
31
2009-01-07T04:51:26Z
[ "python", "xml" ]
I need to load an XML file and put the contents into an object-oriented structure. I want to take this: ``` <main> <object1 attr="name">content</object> </main> ``` and turn it into something like this: ``` main main.object1 = "content" main.object1.attr = "name" ``` It'll have a more complicated structure than...
It's worth to have a look at <http://lxml.de/objectify.html> ``` >>> xml = """<main> ... <object1 attr="name">content</object1> ... <object1 attr="foo">contenbar</object1> ... <test>me</test> ... </main>""" >>> from lxml import objectify >>> main = objectify.fromstring(xml) >>> main.object1[0] 'content' >>> main.o...
Pythonic equivalent of unshift or redo?
418,915
12
2009-01-07T01:59:07Z
418,946
13
2009-01-07T02:12:11Z
[ "python", "redo" ]
I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop. For example, suppose I'm picking apples from a tree. My fruit basket can only hol...
Why bother with unshifting when the else clause should always occur? ``` for apple in tree: if (apple.weight + basket.weight) > 10: send(basket) basket.clear() basket.add(apple) ``` Anyway, I'm fairly certain that Python doesn't have the sort of behavior you're looking for.
Pythonic equivalent of unshift or redo?
418,915
12
2009-01-07T01:59:07Z
418,987
16
2009-01-07T02:27:28Z
[ "python", "redo" ]
I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop. For example, suppose I'm picking apples from a tree. My fruit basket can only hol...
> I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop. Here's a simple solution: ``` class MyIterator(object): # undo-able iterator...
Python Threads - Critical Section
419,145
10
2009-01-07T03:58:18Z
419,155
14
2009-01-07T04:07:50Z
[ "python", "multithreading", "language-agnostic" ]
What is the "critical section" of a thread (in Python)? > A thread enters the critical section > by calling the acquire() method, which > can either be blocking or > non-blocking. A thread exits the > critical section, by calling the > release() method. - [Understanding Threading in Python, Linux Gazette](http://linu...
A critical section of code is one that can only be executed by one thread at a time. Take a chat server for instance. If you have a thread for each connection (i.e., each end user), one "critical section" is the spooling code (sending an incoming message to all the clients). If more than one thread tries to spool a mes...
Python Threads - Critical Section
419,145
10
2009-01-07T03:58:18Z
419,213
8
2009-01-07T04:42:43Z
[ "python", "multithreading", "language-agnostic" ]
What is the "critical section" of a thread (in Python)? > A thread enters the critical section > by calling the acquire() method, which > can either be blocking or > non-blocking. A thread exits the > critical section, by calling the > release() method. - [Understanding Threading in Python, Linux Gazette](http://linu...
Other people have given very nice definitions. Here's the classic example: ``` import threading account_balance = 0 # The "resource" that zenazn mentions. account_balance_lock = threading.Lock() def change_account_balance(delta): global account_balance with account_balance_lock: # Critical section is ...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
419,174
61
2009-01-07T04:14:23Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
`if __name__ == "__main__"` is the part that runs when the script is run from (say) the command line using a command like `python myscript.py`.
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
419,185
2,443
2009-01-07T04:26:43Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special `__name__` variable to have a value `"__m...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
419,189
697
2009-01-07T04:28:23Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
When your script is run by passing it as a command to the Python interpreter, ``` python myscript.py ``` all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets ran. Unlike other languages, there's no `main()` function that g...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
419,986
337
2009-01-07T11:35:17Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
The simplest explanation for the `__name__` variable (imho) is the following: Create the following files. ``` # a.py import b ``` and ``` # b.py print "Hello World from %s!" % __name__ if __name__ == '__main__': print "Hello World again from %s!" % __name__ ``` Running them will get you this output: ``` $ py...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
15,789,709
19
2013-04-03T14:09:11Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
When there are certain statements in our module (`M.py`), we want to be executed when it 'll be running as main (not imported), in that case we can place those statements (test-cases, print statements) under this if block. As by default (when module running as main, not imported) the `__name__` variable is set to `"__m...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
20,158,605
241
2013-11-23T04:38:25Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
> # What does the `if __name__ == "__main__":` do? The global variable, `__name__`, in the module that is the entry point to your program, is `'__main__'`. So, code in this `if` block will only run if that module is the entry point to your program. --- Why do we need this? # Developing and Testing Your Code Say y...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
20,517,795
15
2013-12-11T11:23:53Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
When you run Python interactively the local `__name__` variable is assigned a value of `__main__`. Likewise, when you execute a Python module from the command line, rather than importing it into another module, its `__name__` attribute is assigned a value of `__main__`, rather than the actual name of the module. In thi...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
26,369,628
28
2014-10-14T20:22:55Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
> # What does `if __name__ == “__main__”:` do? `__name__` is a global variable (in Python, global actually means on the [module level](https://docs.python.org/tutorial/modules.html#modules)) that exists in all namespaces. It is typically the module's name (as a `str` type). As the only special case, however, in w...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
28,051,929
15
2015-01-20T17:48:56Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
Let's look at the answer in a more abstract way: Suppose we have this code in x.py: ``` ... <Block A> if __name__ == '__main__': <Block B> ... ``` Blocks A and B are run when we are running "x.py". But just block A (and not B) is run when we are running another module, "y.py" for example, in which x.y is import...
What does `if __name__ == "__main__":` do?
419,163
2,184
2009-01-07T04:11:00Z
33,916,552
7
2015-11-25T12:26:57Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does the `if __name__ == "__main__":` do? ``` # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock()...
There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the **\_\_name\_\_** variable/attribute: When Python loads a source code file, it executes all of the code found in it. (Note that it doesn't call all...
Anyone know of a good Python based web crawler that I could use?
419,235
67
2009-01-07T04:53:21Z
419,259
56
2009-01-07T05:13:20Z
[ "python", "web-crawler" ]
I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of [open source crawlers](http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers) but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia pa...
* [Mechanize](http://wwwsearch.sourceforge.net/mechanize/) is my favorite; great high-level browsing capabilities (super-simple form filling and submission). * [Twill](http://twill.idyll.org/) is a simple scripting language built on top of Mechanize * [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) + [ur...
Anyone know of a good Python based web crawler that I could use?
419,235
67
2009-01-07T04:53:21Z
421,645
44
2009-01-07T19:11:00Z
[ "python", "web-crawler" ]
I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of [open source crawlers](http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers) but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia pa...
Use [Scrapy](http://scrapy.org/). It is a twisted-based web crawler framework. Still under heavy development but it works already. Has many goodies: * Built-in support for parsing HTML, XML, CSV, and Javascript * A media pipeline for scraping items with images (or any other media) and download the image files as well...
Grabbing text from a webpage
419,260
2
2009-01-07T05:14:40Z
419,268
11
2009-01-07T05:17:21Z
[ "python", "c", "text", "webpage" ]
I would like to write a program that will find bus stop times and update my personal webpage accordingly. If I were to do this manually I would 1. Visit www.calgarytransit.com 2. Enter a stop number. ie) 9510 3. Click the button "next bus" The results may look like the following: > 10:16p Route 154 > 10:46p Route 1...
[Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick%20Start) is a Python library designed for parsing web pages. Between it and [urllib2](http://docs.python.org/library/urllib2.html) ([urllib.request](http://docs.python.org/py3k/library/urllib.request) in Python 3) you should be able ...
How to maintain lists and dictionaries between function calls in Python?
419,379
4
2009-01-07T06:21:19Z
419,389
14
2009-01-07T06:25:35Z
[ "python", "variables", "function-calls" ]
I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls Suppose the dic is : ``` a = {'a':1,'b':2,'c':3} ``` At first call,say,I changed a[a] to 100 Dict becomes `a = {'a':100,'b':2,'c':3}` At another call,i changed a[b] to 200...
You could use a [static variable](http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function): ``` def foo(k, v): foo.a[k] = v foo.a = {'a': 1, 'b': 2, 'c': 3} foo('a', 100) foo('b', 200) print foo.a ```
How to maintain lists and dictionaries between function calls in Python?
419,379
4
2009-01-07T06:21:19Z
419,391
7
2009-01-07T06:26:29Z
[ "python", "variables", "function-calls" ]
I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls Suppose the dic is : ``` a = {'a':1,'b':2,'c':3} ``` At first call,say,I changed a[a] to 100 Dict becomes `a = {'a':100,'b':2,'c':3}` At another call,i changed a[b] to 200...
If 'a' is being created inside the function. It is going out of scope. Simply create it outside the function(and before the function is called). By doing this the list/hash will not be deleted after the program leaves the function. ``` a = {'a':1,'b':2,'c':3} # call you funciton here ```
How to maintain lists and dictionaries between function calls in Python?
419,379
4
2009-01-07T06:21:19Z
419,924
14
2009-01-07T11:13:21Z
[ "python", "variables", "function-calls" ]
I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls Suppose the dic is : ``` a = {'a':1,'b':2,'c':3} ``` At first call,say,I changed a[a] to 100 Dict becomes `a = {'a':100,'b':2,'c':3}` At another call,i changed a[b] to 200...
You might be talking about a callable object. ``` class MyFunction( object ): def __init__( self ): self.rememberThis= dict() def __call__( self, arg1, arg2 ): # do something rememberThis['a'] = arg1 return someValue myFunction= MyFunction() ``` From then on, use myFunction as...
Migrating from CPython to Jython
420,792
23
2009-01-07T15:46:10Z
421,125
7
2009-01-07T17:01:35Z
[ "python", "migration", "jython", "cpython" ]
I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar? From reading the [Jython site](http://jython.sou...
So far, I have noticed two further issues: * String interning 'a' is 'a' is not guaranteed (and it is just an implementation fluke on CPython). This could be a serious problem, and really was in one of the libraries I was porting (Jinja2). Unit tests are (as always) your best friends! ``` Jython 2.5b0 (trunk:5540, Oc...
Migrating from CPython to Jython
420,792
23
2009-01-07T15:46:10Z
2,578,481
9
2010-04-05T13:03:03Z
[ "python", "migration", "jython", "cpython" ]
I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar? From reading the [Jython site](http://jython.sou...
First off, I have to say the Jython implementation is very good. Most things "just work". Here are a few things that I have encountered: * C modules are not available, of course. * open('file').read() doesn't automatically close the file. This has to do with the difference in the garbage collector. This can cause iss...
How do I enable push-notification for IMAP (Gmail) using Python imaplib?
421,178
24
2009-01-07T17:13:32Z
421,343
13
2009-01-07T18:04:46Z
[ "python", "gmail", "imap" ]
Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls. I see that the IMAP protocol supports this with the...
There isn't something in imaplib that does this, AFAIK (disclamer: I know very little about Python), however, it seems that someone has implemented an IDLE extension for Python which has the same interface as imaplib (which you can swap out with no changes to existing code, apparently): <http://www.cs.usyd.edu.au/~pie...
Python script to list users and groups
421,618
15
2009-01-07T19:05:11Z
421,651
13
2009-01-07T19:12:27Z
[ "python", "scripting", "sysadmin", "user", "groups" ]
I'm attempting to code a script that outputs each user and their group on their own line like so: ``` user1 group1 user2 group1 user3 group2 ... user10 group6 ``` etc. I'm writing up a script in python for this but was wondering how SO might do this. Thanks! p.s. Take a whack at it in any language but I'd p...
the `grp` module is your friend. Look at `grp.getgrall()` to get a list of all groups and their members. **EDIT** example: ``` import grp groups = grp.getgrall() for group in groups: for user in group[3]: print user, group[0] ```
Python script to list users and groups
421,618
15
2009-01-07T19:05:11Z
421,670
13
2009-01-07T19:14:47Z
[ "python", "scripting", "sysadmin", "user", "groups" ]
I'm attempting to code a script that outputs each user and their group on their own line like so: ``` user1 group1 user2 group1 user3 group2 ... user10 group6 ``` etc. I'm writing up a script in python for this but was wondering how SO might do this. Thanks! p.s. Take a whack at it in any language but I'd p...
For \*nix, you have the [pwd](http://docs.python.org/2/library/pwd.html) and [grp](http://docs.python.org/2/library/grp.html) modules. You iterate through `pwd.getpwall()` to get all users. You look up their group names with `grp.getgrgid(gid)`. ``` import pwd, grp for p in pwd.getpwall(): print p[0], grp.getgrgid...
How can the user communicate with my python script using the shell?
422,091
3
2009-01-07T21:07:23Z
422,121
7
2009-01-07T21:14:14Z
[ "python" ]
How can I implement the following in python? ``` #include <iostream> int main() { std::string a; std::cout << "What is your name? "; std::cin >> a; std::cout << std::endl << "You said: " << a << std::endl; } ``` Output: > What is your name? Nick > > You said: Nick
Call ``` name = raw_input('What is your name?') ``` and ``` print 'You said', name ```
How to access the user profile in a Django template?
422,140
72
2009-01-07T21:19:13Z
422,153
119
2009-01-07T21:24:09Z
[ "python", "django", "django-templates" ]
I'm storing some additional per-user information using the [`AUTH_PROFILE_MODULE`](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users). We can access the user in a Django template using `{{ request.user }}` but how do we access fields in the profile since the profile is only a...
Use `{{ request.user.get_profile.whatever }}`. Django's templating language automatically calls things that are callable - in this case, the `.get_profile()` method.
How to access the user profile in a Django template?
422,140
72
2009-01-07T21:19:13Z
422,218
7
2009-01-07T21:41:55Z
[ "python", "django", "django-templates" ]
I'm storing some additional per-user information using the [`AUTH_PROFILE_MODULE`](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users). We can access the user in a Django template using `{{ request.user }}` but how do we access fields in the profile since the profile is only a...
Yes it is possible to access profile from template using request.user.get\_profile However there is a small **caveat**: not all users will have profiles, which was in my case with admin users. So calling directly `{{ request.user.get_profile.whatever }}` from the template will cause an error in such cases. If you are...
How to access the user profile in a Django template?
422,140
72
2009-01-07T21:19:13Z
2,118,943
17
2010-01-22T17:00:28Z
[ "python", "django", "django-templates" ]
I'm storing some additional per-user information using the [`AUTH_PROFILE_MODULE`](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users). We can access the user in a Django template using `{{ request.user }}` but how do we access fields in the profile since the profile is only a...
Not sure why it's different for me, but I need to use {{user}} rather than {{request.user}}.
Fixed-point arithmetic
422,247
3
2009-01-07T21:48:13Z
422,318
8
2009-01-07T22:00:42Z
[ "python", "math" ]
Does anyone know of a library to do fixed point arithmetic in Python? Or, does anyone has sample code?
If you are interested in doing fixed point arithmetic, the Python Standard Library has a [decimal](http://docs.python.org/library/decimal.html) module that can do it. Actually, it has a more flexible floating point ability than the built-in too. By flexible I mean that it: * Has "signals" for various exceptional cond...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
423,401
129
2009-01-08T05:59:04Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
You may want to explore the notion of [namespaces](http://docs.python.org/reference/datamodel.html). In Python, the [module](http://docs.python.org/tutorial/modules.html) is the natural place for *global* data: > Each module has its own private symbol table, which is used as the global symbol table by all functions de...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
423,596
2,407
2009-01-08T08:39:44Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
You can use a global variable in other functions by declaring it as `global` in each function that assigns to it: ``` globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_globvar(): print globvar # No need for global declaration to re...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
423,641
28
2009-01-08T09:03:33Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
If you want to refer to global variable in a function, you can use **global** keyword to declare which variables are global. You don't have to use it in all cases (as someone here incorrectly claims) - if the name referenced in an expression cannot be found in local scope or scopes in the functions in which this functi...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
423,668
519
2009-01-08T09:19:55Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces. Say you've got a module like this: ``` # sample.py myGlobal = 5 def func1(): myGlobal = 42 def func2(): print myGlobal func1() func2() ``` You might expect...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
427,818
11
2009-01-09T11:56:19Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation. If you didn't have to explicitly spe...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
6,664,227
50
2011-07-12T12:35:08Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
Python uses a simple heuristic to decide which scope it should load a variable from, between local and global. If a variable name appears on the left hand side of an assignment, but is not declared global, it is assumed to be local. If it does not appear on the left hand side of an assignment, it is assumed to be globa...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
19,151,605
14
2013-10-03T05:41:16Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
Global variables are much more fun when you deal with parallel execution. Here is an example of using a global variable within multiprocessing. We can clearly see that each process works with its own copy of the variable: ``` import multiprocessing import time import os import sys import random def worker(a): oldV...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
19,347,254
8
2013-10-13T16:07:41Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
As it turns out the answer is always simple. Here is a small sample module. It is is a way to show it in a main definition: ``` def five(enterAnumber,sumation): global helper helper = enterAnumber + sumation def isTheNumber(): return helper ``` Here is a way to show it in a main definition: ``` import...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
24,572,187
21
2014-07-04T10:23:56Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
In addition to already existing answers and to make this more confusing: > In Python, variables that are only referenced inside a function are > **implicitly global**. If a variable is assigned a new value anywhere > within the function’s body, it’s assumed to be a **local**. If a variable > is ever assigned a new...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
27,287,648
8
2014-12-04T06:27:43Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
What you are saying is to use the method like this: ``` globvar = 5 def f(): var = globvar print(var) f()** #prints 5 ``` but the better way is to use the global variable like this: ``` globavar = 5 def f(): global globvar print(globvar) f() #prints 5 ``` both give the same output.
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
27,580,376
8
2014-12-20T12:45:26Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
You need to reference the global variable in every function you want to use. As follows: ``` var = "test" def printGlobalText(): global var #wWe are telling to explicitly use the global version var = "global from printGlobalText fun." print "var from printGlobalText: " + var def printLocalText(): #W...
Using global variables in a function other than the one that created them
423,379
1,686
2009-01-08T05:45:02Z
34,559,513
10
2016-01-01T19:55:14Z
[ "python", "global-variables", "scope" ]
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
> # If I create a global variable in one function, how can I use that variable in another function? We can create a global with the following function: ``` def create_global_variable(): global global_variable # must declare it to be a global first # modifications are thus reflected on the module's global scop...
Python unittest with expensive setup
423,483
18
2009-01-08T07:00:36Z
425,483
21
2009-01-08T19:12:44Z
[ "python", "unit-testing" ]
My test file is basically: ``` class Test(unittest.TestCase): def testOk(): pass if __name__ == "__main__": expensiveSetup() try: unittest.main() finally: cleanUp() ``` However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't...
If you use Python >= 2.7 (or [unittest2](http://pypi.python.org/pypi/unittest2) for Python >= 2.4 & <= 2.6), the best approach would be be to use ``` def setUpClass(cls): # ... setUpClass = classmethod(setUpClass) ``` to perform some initialization once for all tests belonging to the given class. And to perform ...
Best Way To Determine if a Sequence is in another sequence in Python
425,604
15
2009-01-08T19:46:10Z
425,825
14
2009-01-08T20:42:46Z
[ "python", "algorithm", "sequence" ]
This is a generalization of the "string contains substring" problem to (more) arbitrary types. Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts: Example usage (Seque...
I second the Knuth-Morris-Pratt algorithm. By the way, your problem (and the KMP solution) is exactly recipe 5.13 in [Python Cookbook](http://rads.stackoverflow.com/amzn/click/0596007973) 2nd edition. You can find the related code at <http://code.activestate.com/recipes/117214/> It finds *all* the correct subsequences...
Django on IronPython
425,990
50
2009-01-08T21:16:01Z
426,257
8
2009-01-08T22:20:23Z
[ "python", "django", "ironpython" ]
I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?
[Here's a database provider that runs on .NET & that works with Django](http://blogs.msdn.com/dinoviehland/archive/2008/03/17/ironpython-ms-sql-and-pep-249.aspx)
Django on IronPython
425,990
50
2009-01-08T21:16:01Z
518,317
25
2009-02-05T22:40:08Z
[ "python", "django", "ironpython" ]
I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?
Besides the Jeff Hardy blog post on [Django + IronPython](http://jdhardy.blogspot.com/2008/12/django-ironpython.html) mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy\_install and zlib. The first is [Solving the zlib problem](http:...
How do I mock the Python method OptionParser.error(), which does a sys.exit()?
426,500
14
2009-01-08T23:37:31Z
426,624
12
2009-01-09T00:24:15Z
[ "python", "unit-testing", "mocking", "optparse" ]
I'm trying to unit test some code that looks like this: ``` def main(): parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool') parser.add_option('--foo', action='store', help='The foo option is self-explanatory') options, arguments = parser.parse_args() if not options.foo: ...
Will this work instead of `assertEquals`? ``` self.assertRaises(SystemExit, sut.main, 2) ``` This should catch the `SystemExit` exception and prevent the script from terminating.
PyObjc vs RubyCocoa for Mac development: Which is more mature?
426,607
8
2009-01-09T00:16:24Z
426,703
11
2009-01-09T01:08:54Z
[ "python", "ruby", "cocoa", "pyobjc", "ruby-cocoa" ]
I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming. So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa). I know that ideally to get the...
While you say you "don't have time" to learn technologies independently the fastest route to learning Cocoa will still be to learn it in its native language: Objective-C. Once you understand Objective-C and have gotten over the initial learning curve of the Cocoa frameworks you'll have a much easier time picking up eit...
PyObjc vs RubyCocoa for Mac development: Which is more mature?
426,607
8
2009-01-09T00:16:24Z
429,727
8
2009-01-09T21:02:42Z
[ "python", "ruby", "cocoa", "pyobjc", "ruby-cocoa" ]
I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming. So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa). I know that ideally to get the...
I would echo Chris' assesment and will expand a bit on why you should learn Objective-C to learn Cocoa. As Chris says, Objective-C is the foundation and native language of Cocoa and many of its paradigms are inextricably linked with that lineage. In particular, selectors and dynamic message resolution and ability to mo...
What is a "slug" in Django?
427,102
273
2009-01-09T04:52:26Z
427,111
13
2009-01-09T04:56:10Z
[ "python", "django", "django-models", "slug" ]
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](http://docs.djangoproject.com/en/dev/glossary/).)
From [here](http://jeffcroft.com/blog/2006/may/02/django-non-programmers/). > “Slug” is a newspaper term, but what > it means here is the final bit of the > URL. For example, a post with the > title, “A bit about Django” would > become, “bit-about-django” > automatically (you can, of course, > change it ea...
What is a "slug" in Django?
427,102
273
2009-01-09T04:52:26Z
427,125
13
2009-01-09T05:02:48Z
[ "python", "django", "django-models", "slug" ]
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](http://docs.djangoproject.com/en/dev/glossary/).)
It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in <http://stackoverflow.com/questions/427102/in-django-what-is-a-slug> the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the [page served](http://st...
What is a "slug" in Django?
427,102
273
2009-01-09T04:52:26Z
427,160
355
2009-01-09T05:31:47Z
[ "python", "django", "django-models", "slug" ]
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](http://docs.djangoproject.com/en/dev/glossary/).)
It's a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL. I'd advise to generate the slug, using a function, given a title (or other piece of data), rather than setting it manually. An example: ``` <title> The 46 Year Old Virgin </title...
What is a "slug" in Django?
427,102
273
2009-01-09T04:52:26Z
427,201
34
2009-01-09T06:01:06Z
[ "python", "django", "django-models", "slug" ]
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](http://docs.djangoproject.com/en/dev/glossary/).)
As a bit of history, the term 'slug' comes from the world of newspaper editing. It's the informal name given to a story during the production process. As the story winds its torturous path from beat reporter through to editor through to the "printing presses", this is the name it is referenced by, e.g., "Have you fixe...
What is a "slug" in Django?
427,102
273
2009-01-09T04:52:26Z
1,282,172
58
2009-08-15T15:45:33Z
[ "python", "django", "django-models", "slug" ]
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](http://docs.djangoproject.com/en/dev/glossary/).)
May I be complete to this : The term **"slug"** has to do with casting metal, lead, in this case, out of which the press fonts were made of. Every Paper then, had its fonts factory, regularily, re-melted and recasted in fresh molds. Because after many prints they were worned out. Apprentice like me started their caree...
How can I get the source code of a Python function?
427,453
127
2009-01-09T09:02:37Z
427,504
120
2009-01-09T09:25:54Z
[ "python", "function" ]
Suppose I have a Python function as defined below: ``` def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a ``` I can get the name of the function using `foo.func_name`. How can I programmatically get its source code, as I typed above?
The [inspect module](http://docs.python.org/library/inspect.html?highlight=inspect#retrieving-source-code) has methods for retreiving source code from python objects. Seemingly it only works if the source is located in a file though. If you had that I guess you wouldn't need to get the source from the object.
How can I get the source code of a Python function?
427,453
127
2009-01-09T09:02:37Z
427,533
180
2009-01-09T09:44:38Z
[ "python", "function" ]
Suppose I have a Python function as defined below: ``` def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a ``` I can get the name of the function using `foo.func_name`. How can I programmatically get its source code, as I typed above?
If the function is from a source file available on the filesystem, then [`inspect.getsourcelines(foo)`](https://docs.python.org/3/library/inspect.html#inspect.getsourcelines) might be of help. I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve it...
How can I get the source code of a Python function?
427,453
127
2009-01-09T09:02:37Z
17,358,307
45
2013-06-28T06:11:18Z
[ "python", "function" ]
Suppose I have a Python function as defined below: ``` def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a ``` I can get the name of the function using `foo.func_name`. How can I programmatically get its source code, as I typed above?
`dis` is your friend if the source code is not available: ``` >>> import dis >>> def foo(arg1,arg2): ... #do something with args ... a = arg1 + arg2 ... return a ... >>> dis.dis(foo) 3 0 LOAD_FAST 0 (arg1) 3 LOAD_FAST 1 (arg2) 6 BINARY_A...
How can I get the source code of a Python function?
427,453
127
2009-01-09T09:02:37Z
21,339,166
27
2014-01-24T17:51:36Z
[ "python", "function" ]
Suppose I have a Python function as defined below: ``` def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a ``` I can get the name of the function using `foo.func_name`. How can I programmatically get its source code, as I typed above?
While I'd generally agree that `inspect` is a good answer, I'd disagree that you can't get the source code of objects defined in the interpreter. If you use `dill.source.getsource` from [`dill`](https://github.com/uqfoundation/dill), you can get the source of functions and lambdas, even if they are defined interactivel...
How can I get the source code of a Python function?
427,453
127
2009-01-09T09:02:37Z
25,107,178
14
2014-08-03T17:23:42Z
[ "python", "function" ]
Suppose I have a Python function as defined below: ``` def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a ``` I can get the name of the function using `foo.func_name`. How can I programmatically get its source code, as I typed above?
To expand on runeh's answer: ``` >>> def foo(a): ... x = 2 ... return x + a >>> import inspect >>> inspect.getsource(foo) u'def foo(a):\n x = 2\n return x + a\n' print inspect.getsource(foo) def foo(a): x = 2 return x + a ``` EDIT: As pointed out by @0sh this example works using `ipython` but not...
How can I get the source code of a Python function?
427,453
127
2009-01-09T09:02:37Z
37,111,797
12
2016-05-09T09:11:05Z
[ "python", "function" ]
Suppose I have a Python function as defined below: ``` def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a ``` I can get the name of the function using `foo.func_name`. How can I programmatically get its source code, as I typed above?
If you are using IPython, then you need to type "foo??" ``` In [19]: foo?? Signature: foo(arg1, arg2) Source: def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a File: ~/Desktop/<ipython-input-18-3174e3126506> Type: function ```
Ordered lists in django
428,149
10
2009-01-09T14:06:13Z
428,189
18
2009-01-09T14:17:26Z
[ "python", "django", "django-models" ]
i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this: ``` class Item(models.Model): data = models.TextField() order = models.IntegerField() ``` or like this: ``` class Item(models.Model): data = models.TextField() next = m...
Essentially, the second solution you propose is a linked list. Linked list implemented at the database level are usually not a good idea. To retrieve a list of `n` elements, you will need `n` database access (or use complicated queries). Performance wise, retrieving a list in O(n) is awfully not efficient. In regular ...
Can I use urllib to submit a SOAP request?
429,164
3
2009-01-09T18:30:09Z
429,349
7
2009-01-09T19:23:51Z
[ "python", "soap" ]
I have a SOAP request that is known to work using a tool like, say, SoapUI, but I am trying to get it to work using urllib. This is what I have tried so far and it did not work: ``` import urllib f = "".join(open("ws_request_that_works_in_soapui", "r").readlines()) urllib.urlopen('http://url.com/to/Router?wsdl', f) `...
Well, I answered my own question ``` import httplib f = "".join(open('ws_request', 'r')) webservice = httplib.HTTP('localhost', 8083) webservice.putrequest("POST", "Router?wsdl") webservice.putheader("User-Agent", "Python post") webservice.putheader("Content-length", "%d" % len(f)) webservice.putheader("SOAPAction",...
what's the pythonic way to count the occurrence of an element in a list?
429,414
9
2009-01-09T19:42:32Z
429,442
9
2009-01-09T19:49:50Z
[ "python" ]
this is what I did. is there a better way in python? ``` for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 ``` Thanks
Single element: ``` a_list.count(k) ``` All elements: ``` counts = dict((k, a_list.count(k)) for k in set(a_list)) ```
what's the pythonic way to count the occurrence of an element in a list?
429,414
9
2009-01-09T19:42:32Z
429,469
7
2009-01-09T19:55:59Z
[ "python" ]
this is what I did. is there a better way in python? ``` for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 ``` Thanks
I dunno, it basically looks fine to me. Your code is simple and easy to read which is an important part of what I consider pythonic. You could trim it up a bit like so: ``` for k in a_list: kvMap[k] = 1 + kvMap.get(k,0) ```
what's the pythonic way to count the occurrence of an element in a list?
429,414
9
2009-01-09T19:42:32Z
429,491
14
2009-01-09T20:01:37Z
[ "python" ]
this is what I did. is there a better way in python? ``` for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 ``` Thanks
Use defaultdict ``` from collections import defaultdict kvmap= defaultdict(int) for k in a_list: kvmap[k] += 1 ```
Regular expression: replace the suffix of a string ending in '.js' but not 'min.js'
430,047
3
2009-01-09T22:47:16Z
430,064
9
2009-01-09T22:53:16Z
[ "python", "regex" ]
Assume infile is a variable holding the name of an input file, and similarly outfile for output file. If infile ends in **.js**, I'd like to replace with **.min.js** and that's easy enough (I think). **outfile = re.sub(r'\b.js$', '.min.js', infile)** But my question is if infile ends in **.min.js**, then I do not wan...
You want to do a negative lookbehind assertion. For instance, ``` outfile = re.sub(r"(?<!\.min)\.js$", ".min.js", infile) ``` You can find more about this here: <http://docs.python.org/library/re.html#regular-expression-syntax>
How to split strings into text and number?
430,079
17
2009-01-09T23:02:16Z
430,102
25
2009-01-09T23:12:01Z
[ "python", "string", "split" ]
I'd like to split strings like these 'foofo21' 'bar432' 'foobar12345' into ['foofo', '21'] ['bar', '432'] ['foobar', '12345'] Does somebody know an easy and simple way to do this in python?
I would approach this by using `re.match` in the following way: ``` match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I) if match: items = match.groups() # items is ("foo", "21") ```
How to split strings into text and number?
430,079
17
2009-01-09T23:02:16Z
430,105
8
2009-01-09T23:12:16Z
[ "python", "string", "split" ]
I'd like to split strings like these 'foofo21' 'bar432' 'foobar12345' into ['foofo', '21'] ['bar', '432'] ['foobar', '12345'] Does somebody know an easy and simple way to do this in python?
``` >>> r = re.compile("([a-zA-Z]+)([0-9]+)") >>> m = r.match("foobar12345") >>> m.group(1) 'foobar' >>> m.group(2) '12345' ``` So, if you have a list of strings with that format: ``` import re r = re.compile("([a-zA-Z]+)([0-9]+)") strings = ['foofo21', 'bar432', 'foobar12345'] print [r.match(string).groups() for str...
How to split strings into text and number?
430,079
17
2009-01-09T23:02:16Z
430,665
10
2009-01-10T06:17:25Z
[ "python", "string", "split" ]
I'd like to split strings like these 'foofo21' 'bar432' 'foobar12345' into ['foofo', '21'] ['bar', '432'] ['foobar', '12345'] Does somebody know an easy and simple way to do this in python?
``` >>> def mysplit(s): ... head = s.rstrip('0123456789') ... tail = s[len(head):] ... return head, tail ... >>> [mysplit(s) for s in ['foofo21', 'bar432', 'foobar12345']] [('foofo', '21'), ('bar', '432'), ('foobar', '12345')] >>> ```
Regex for managing escaped characters for items like string literals
430,759
9
2009-01-10T08:45:09Z
5,455,705
15
2011-03-28T07:10:00Z
[ "python", "regex" ]
I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following: ``` import re regexc = re.compil...
## re\_single\_quote = r"`'[^'\\]*(?:\\.[^'\\]*)*'"` First note that MizardX's answer is 100% accurate. I'd just like to add some additional recommendations regarding efficiency. Secondly, I'd like to note that this problem was solved and optimized long ago - See: [Mastering Regular Expressions (3rd Edition)](http://r...
Regex for links in html text
430,966
7
2009-01-10T13:45:28Z
430,976
16
2009-01-10T13:52:47Z
[ "python", "html", "regex", "hyperlink", "href" ]
I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the `<link href...` tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links? Adam **UPDATE:** I am actually l...
Regexes with HTML get messy. Just use a DOM parser like Beautiful Soup.
Regex for links in html text
430,966
7
2009-01-10T13:45:28Z
431,425
8
2009-01-10T17:53:02Z
[ "python", "html", "regex", "hyperlink", "href" ]
I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the `<link href...` tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links? Adam **UPDATE:** I am actually l...
As others have suggested, if real-time-like performance isn't necessary, BeautifulSoup is a good solution: ``` import urllib2 from BeautifulSoup import BeautifulSoup html = urllib2.urlopen("http://www.google.com").read() soup = BeautifulSoup(html) all_links = soup.findAll("a") ``` As for the second question, yes, HT...
How can I programatically change the background in Mac OS X?
431,205
27
2009-01-10T16:06:48Z
431,279
34
2009-01-10T16:38:06Z
[ "python", "image", "osx" ]
How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?
From python, if you have [appscript](http://appscript.sourceforge.net/) installed (`sudo easy_install appscript`), you can simply do ``` from appscript import app, mactypes app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg')) ``` Otherwise, this applescript will change the desktop background ``` te...
How can I programatically change the background in Mac OS X?
431,205
27
2009-01-10T16:06:48Z
2,119,076
21
2010-01-22T17:18:27Z
[ "python", "image", "osx" ]
How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?
If you are doing this for the current user, you can run, from a shell: ``` defaults write com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}' ``` Or, as root, for another user: ``` /usr/bin/defaults write /Users/joeuser/Library/Preferences/com.apple...
How can I programatically change the background in Mac OS X?
431,205
27
2009-01-10T16:06:48Z
6,738,885
11
2011-07-18T20:17:05Z
[ "python", "image", "osx" ]
How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?
I had this same question, *except* that I wanted to change the wallpaper on *all attached monitors.* Here's a Python script using `appscript` (mentioned above; `sudo easy_install appscript`) which does just that. ``` #!/usr/bin/python from appscript import * import argparse def __main__(): parser = argparse.Argume...
How do I "cd" in Python?
431,684
343
2009-01-10T20:28:16Z
431,715
338
2009-01-10T20:41:50Z
[ "python" ]
`cd` as in the shell command to change the working directory. How do I change the current working directory in Python?
You can change the working directory with ``` os.chdir(path) ``` There are two best practices to follow when using this method: 1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the ol...
How do I "cd" in Python?
431,684
343
2009-01-10T20:28:16Z
431,720
98
2009-01-10T20:43:26Z
[ "python" ]
`cd` as in the shell command to change the working directory. How do I change the current working directory in Python?
I would use `os.chdir` probably. It works like this: ``` os.chdir("/path/to/change/to") ``` By the way, if you need to figure out your current path, use `os.getcwd()`. More here: <http://effbot.org/librarybook/os.htm>
How do I "cd" in Python?
431,684
343
2009-01-10T20:28:16Z
431,747
18
2009-01-10T21:02:31Z
[ "python" ]
`cd` as in the shell command to change the working directory. How do I change the current working directory in Python?
If you're using a relatively new version of Python, you can also use a context manager, such as [this one](http://software.clapper.org/grizzled-python/epydoc/grizzled.os-module.html#working_directory): ``` from __future__ import with_statement from grizzled.os import working_directory with working_directory(path_to_d...
How do I "cd" in Python?
431,684
343
2009-01-10T20:28:16Z
13,197,763
194
2012-11-02T15:00:21Z
[ "python" ]
`cd` as in the shell command to change the working directory. How do I change the current working directory in Python?
Here's an example of a context manager to change the working directory. It is simpler than an [ActiveState version](http://code.activestate.com/recipes/576620-changedirectory-context-manager) referred to elsewhere, but this gets the job done. ### Context Manager: `cd` ``` import os class cd: """Context manager f...
How do I "cd" in Python?
431,684
343
2009-01-10T20:28:16Z
16,694,919
7
2013-05-22T14:48:03Z
[ "python" ]
`cd` as in the shell command to change the working directory. How do I change the current working directory in Python?
As already pointed out by others, all the solutions above only change the working directory of the current process. This is lost when you exit back to the Unix shell. If desperate you **can** change the parent shell directory on Unix with this horrible hack: ``` def quote_against_shell_expansion(s): import pipes ...
How do I "cd" in Python?
431,684
343
2009-01-10T20:28:16Z
24,176,022
36
2014-06-12T03:30:46Z
[ "python" ]
`cd` as in the shell command to change the working directory. How do I change the current working directory in Python?
`cd()` is easy to write using a generator and a decorator. ``` from contextlib import contextmanager import os @contextmanager def cd(newdir): prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: yield finally: os.chdir(prevdir) ``` Then, the directory is reverted even afte...
Python csv.reader: How do I return to the top of the file?
431,752
27
2009-01-10T21:04:49Z
431,767
9
2009-01-10T21:11:23Z
[ "python", "csv" ]
When I'm moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like "file.seek(0)". Is there anything like that for the csv module? Thanks ahead of time ;)
You can still use file.seek(0). For instance, look at the following: ``` import csv file_handle = open("somefile.csv", "r") reader = csv.reader(file_handle) # Do stuff with reader file_handle.seek(0) # Do more stuff with reader as it is back at the beginning now ``` This should work since csv.reader is working with t...
Python csv.reader: How do I return to the top of the file?
431,752
27
2009-01-10T21:04:49Z
431,771
43
2009-01-10T21:12:26Z
[ "python", "csv" ]
When I'm moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like "file.seek(0)". Is there anything like that for the csv module? Thanks ahead of time ;)
You can seek the file directly. For example: ``` >>> f = open("csv.txt") >>> c = csv.reader(f) >>> for row in c: print row ['1', '2', '3'] ['4', '5', '6'] >>> f.seek(0) >>> for row in c: print row # again ['1', '2', '3'] ['4', '5', '6'] ```
Ignore python multiple return value
431,866
112
2009-01-10T22:12:49Z
431,868
256
2009-01-10T22:14:42Z
[ "python", "function", "tuples" ]
Say I have a Python function that returns multiple values in a tuple: ``` def func(): return 1, 2 ``` Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this: ``` x, temp = func() ```
You can use `x = func()[0]` to return the first value, `x = func()[1]` to return the second, and so on. If you want to get multiple values at a time, use something like `x, y = func()[2:4]`.
Ignore python multiple return value
431,866
112
2009-01-10T22:12:49Z
431,871
100
2009-01-10T22:18:57Z
[ "python", "function", "tuples" ]
Say I have a Python function that returns multiple values in a tuple: ``` def func(): return 1, 2 ``` Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this: ``` x, temp = func() ```
One common convention is to use a "\_" as a variable name for the elements of the tuple you wish to ignore. For instance: ``` def f(): return 1, 2, 3 _, _, x = f() ```
Ignore python multiple return value
431,866
112
2009-01-10T22:12:49Z
431,872
9
2009-01-10T22:19:44Z
[ "python", "function", "tuples" ]
Say I have a Python function that returns multiple values in a tuple: ``` def func(): return 1, 2 ``` Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this: ``` x, temp = func() ```
Three simple choices. Obvious ``` x, _ = func() x, junk = func() ``` Hideous ``` x = func()[0] ``` And there are ways to do this with a decorator. ``` def val0( aFunc ): def pick0( *args, **kw ): return aFunc(*args,**kw)[0] return pick0 func0= val0(func) ```
Ignore python multiple return value
431,866
112
2009-01-10T22:12:49Z
431,873
11
2009-01-10T22:20:20Z
[ "python", "function", "tuples" ]
Say I have a Python function that returns multiple values in a tuple: ``` def func(): return 1, 2 ``` Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this: ``` x, temp = func() ```
Remember, when you return more than one item, you're really returning a tuple. So you can do things like this: ``` def func(): return 1, 2 print func()[0] # prints 1 print func()[1] # prints 2 ```