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) # -> 2014-12-22 22:48:59.916417 ``` Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+): ``` from datetime import datetime, timezone now = datetime.now(timezone.utc).astimezone() print(now) # -> 2014-12-23 01:49:25.837541+03:00 ```
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.python.org/2/library/datetime.html#strftime-strptime-behavior)). ![strftime format code table](http://i.stack.imgur.com/i6Hg7.jpg)
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 floating point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970 00:00:00, and it is memory light relative to the other representations of time we'll be looking at next: ``` >>> time.time() 1424233311.771502 ``` This timestamp does not account for leap-seconds, so it's not linear - leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping. This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you'll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later). ### `time.ctime` You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don't rely on this to be standard across all systems, as I've seen others expect). This is typically user friendly, but doesn't typically result in strings one can sort chronologically: ``` >>> time.ctime() 'Tue Feb 17 23:21:56 2015' ``` You can hydrate timestamps into human readable form with `ctime` as well: ``` >>> time.ctime(1424233311.771502) 'Tue Feb 17 23:21:51 2015' ``` This conversion is also not good for record-keeping (except in text that will only be parsed by humans - and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish). ## `datetime` module The `datetime` module is also quite useful here: ``` >>> import datetime ``` ### `datetime.datetime.now` The `datetime.now` is a class method that returns the current time. It uses the `time.localtime` without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a `str`), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort: ``` >>> datetime.datetime.now() datetime.datetime(2015, 2, 17, 23, 43, 49, 94252) >>> print(datetime.datetime.now()) 2015-02-17 23:43:51.782461 ``` ### datetime's `utcnow` You can get a datetime object in UTC time, a global standard, by doing this: ``` >>> datetime.datetime.utcnow() datetime.datetime(2015, 2, 18, 4, 53, 28, 394163) >>> print(datetime.datetime.utcnow()) 2015-02-18 04:53:31.783988 ``` UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.) ### datetime timezone aware However, none of the datetime objects we've created so far can be easily converted to various timezones. We can solve that problem with the `pytz` module: ``` >>> import pytz >>> then = datetime.datetime.now(pytz.utc) >>> then datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>) ``` Equivalently, in Python 3 we have the `timezone` class with a utc `timezone` instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy `pytz` module is left as an exercise to the reader): ``` >>> datetime.datetime.now(datetime.timezone.utc) datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc) ``` And we see we can easily convert to timezones from the original utc object. ``` >>> print(then) 2015-02-18 04:55:58.753949+00:00 >>> print(then.astimezone(pytz.timezone('US/Eastern'))) 2015-02-17 23:55:58.753949-05:00 ``` You can also make a naive datetime object aware with the `pytz` timezone `localize` method, or by replacing the tzinfo attribute (with `replace`, this is done blindly), but these are more last resorts than best practices: ``` >>> pytz.utc.localize(datetime.datetime.utcnow()) datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>) >>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc) datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>) ``` The `pytz` module allows us to make our `datetime` objects timezone aware and convert the times to the hundreds of timezones available in the `pytz` module. One could ostensibly serialize this object for UTC time and store *that* in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first. The other ways of viewing times are much more error prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for. If you're displaying the time with Python for the user, `ctime` works nicely, not in a table (it doesn't typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC `datetime` object.
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 of two sets. ``` a = set([1,2,3]) b = set([2,3,4]) c = a|b # = set([1,2,3,4]) ``` Additionally, authors may define operator behavior for custom types, so if `something.property` is a user-defined object, you should check that class definition for an `__or__()` method, which will then define the behavior in your code sample. So, it's impossible to give you a precise answer without knowing the data types for the two operands, but *usually* it will be a bitwise or.
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 File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\__init__.py", line 39, in <module> import core File "C:\svn\svn_urbansim\UrbanSimDev\Builds\working\urbansim\Tools\Python26\lib\site-packages\numpy\core\__init__.py", line 5, in <module> import multiarray ImportError: Module use of python25.dll conflicts with this version of Python. ``` It appears that the existing module is trying to use the `python25.dll` file. Is there any way I can tell it to use the `python26.dll` file instead without modifying the source code?
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 you should be able to compile numpy from sources. Otherwise I think you're stuck with using Python 2.5 on Windows if you need NumPy. The next version of NumPy should have a 2.6 binary, and it's likely to be out within the next month or so. [Edit]: It appears that a pygame developer created a NumPy 1.2.1 binary for Python 2.6 on Windows, available [here](http://www.mail-archive.com/[email protected]/msg14552.html).
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 are they there? I am using a machine set to Australian settings, so there shouldn't be any accented characters or the like. Next, try running this code: ``` for x in string.printable: print x, print for x in string.printable: print x ``` The first line successfully prints all the characters separated by a space. The two odd characters turn out as the Male and Female symbols. The second line successfully prints all the characters EXCEPT THE LAST separated by a line feed. The Male symbol prints; the female symbol is replaced with a missing character (a box). I'm sure Python wasn't intended to be gender-biased, so what gives with the difference?
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 Feed characters. These two characters, along with \t \r and \n, are all printable, and do well defined things on a printer.
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 that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties. Any thoughts on what would be the best way to go about this?
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 for object's with attr=name, optionally look up attrs with regex my_objects = soup.main.findAll("object", attrs={'attr':'name'}) for my_object in my_objects: # this will print a list of the contents of the tag print my_object.contents # if only text is inside the tag you can use this # print tag.string ```
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 that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties. Any thoughts on what would be the best way to go about this?
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.object1[1] 'contenbar' >>> main.object1[0].get("attr") 'name' >>> main.test 'me' ``` Or the other way around to build xml structures: ``` >>> item = objectify.Element("item") >>> item.title = "Best of python" >>> item.price = 17.98 >>> item.price.set("currency", "EUR") >>> order = objectify.Element("order") >>> order.append(item) >>> order.item.quantity = 3 >>> order.price = sum(item.price * item.quantity ... for item in order.item) >>> import lxml.etree >>> print lxml.etree.tostring(order, pretty_print=True) <order> <item> <title>Best of python</title> <price currency="EUR">17.98</price> <quantity>3</quantity> </item> <price>53.94</price> </order> ```
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 hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket. In a language like Perl, I could `unshift()` the apple back onto the tree, and then let the loop expression re-pick the apple: ``` while ($apple = shift(@tree)) { $wt = weight($apple); if ($wt + weight(@basket) > 10) { send(@basket); @basket = (); unshift(@tree, $apple); } else { push(@basket, $element); } } ``` Or else I can also use `redo`, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied. ``` while ($apple = shift(@tree)) { $wt = weight($apple); if ($wt + weight(@basket) > 10) { send(@basket); @basket = (); redo; } else { push(@basket, $apple); } } ``` What would be the most **pythonic** solution for this kind of problem?
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 hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket. In a language like Perl, I could `unshift()` the apple back onto the tree, and then let the loop expression re-pick the apple: ``` while ($apple = shift(@tree)) { $wt = weight($apple); if ($wt + weight(@basket) > 10) { send(@basket); @basket = (); unshift(@tree, $apple); } else { push(@basket, $element); } } ``` Or else I can also use `redo`, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied. ``` while ($apple = shift(@tree)) { $wt = weight($apple); if ($wt + weight(@basket) > 10) { send(@basket); @basket = (); redo; } else { push(@basket, $apple); } } ``` What would be the most **pythonic** solution for this kind of problem?
> 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 wrapper def __init__(self, iterable): super(MyIterator, self).__init__() self.iterator = iter(iterable) self.stack = [] def __iter__(self): return self def next(self): if self.stack: return self.stack.pop() return self.iterator.next() # Raises StopIteration eventually def undo(self, item): self.stack.append(item) ``` ``` for i in MyIterator(xrange(5)): print i 0 1 2 3 4 ``` ``` rng = MyIterator(xrange(5)) rng.next() 0 rng.next() 1 rng.undo(1) rng.next() 1 ```
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://linuxgazette.net/107/pai.html) Also, what is the purpose of a lock?
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 message at once, you'll get BfrIToS mANtwD PIoEmesCEsaSges intertwined, which is obviously no good at all. A lock is something that can be used to synchronize access to a critical section (or resources in general). In our chat server example, the lock is like a locked room with a typewriter in it. If one thread is in there (to type a message out), no other thread can get into the room. Once the first thread is done, he unlocks the room and leaves. Then another thread can go in the room (locking it). "Aquiring" the lock just means "I get the room."
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://linuxgazette.net/107/pai.html) Also, what is the purpose of a lock?
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 within this block. account_balance += delta ``` Let's say that the `+=` operator consists of three subcomponents: * Read the current value * Add the RHS to that value * Write the accumulated value back to the LHS (technically *bind* it in Python terms) If you don't have the `with account_balance_lock` statement and you execute two `change_account_balance` calls in parallel you can end up interleaving the three subcomponent operations in a hazardous manner. Let's say you simultaneously call `change_account_balance(100)` (AKA pos) and `change_account_balance(-100)` (AKA neg). This could happen: ``` pos = threading.Thread(target=change_account_balance, args=[100]) neg = threading.Thread(target=change_account_balance, args=[-100]) pos.start(), neg.start() ``` * pos: read current value -> 0 * neg: read current value -> 0 * pos: add current value to read value -> 100 * neg: add current value to read value -> -100 * pos: write current value -> account\_balance = 100 * neg: write current value -> account\_balance = -100 Because you didn't force the operations to happen in discrete chunks you can have three possible outcomes (-100, 0, 100). The `with [lock]` statement is a single, indivisible operation that says, "Let me be the only thread executing this block of code. If something else is executing, it's cool -- I'll wait." This ensures that the updates to the `account_balance` are "thread-safe" (parallelism-safe). **Note:** There is a caveat to this schema: you have to remember to acquire the `account_balance_lock` (via `with`) every time you want to manipulate the `account_balance` for the code to remain thread-safe. There are ways to make this less fragile, but that's the answer to a whole other question. **Edit:** In retrospect, it's probably important to mention that the `with` statement implicitly calls a blocking `acquire` on the lock -- this is the "I'll wait" part of the above thread dialog. In contrast, a non-blocking acquire says, "If I can't acquire the lock right away, let me know," and then relies on you to check whether you got the lock or not. ``` import logging # This module is thread safe. import threading LOCK = threading.Lock() def run(): if LOCK.acquire(False): # Non-blocking -- return whether we got it logging.info('Got the lock!') LOCK.release() else: logging.info("Couldn't get the lock. Maybe next time") logging.basicConfig(level=logging.INFO) threads = [threading.Thread(target=run) for i in range(100)] for thread in threads: thread.start() ``` I also want to add that the lock's primary purpose is to guarantee the atomicity of acquisition (the indivisibility of the `acquire` across threads), which a simple boolean flag will not guarantee. The semantics of atomic operations are probably also the content of another question.
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 `"__main__"`. If this file is being imported from another module, `__name__` will be set to the module's name. In the case of your script, let's assume that it's executing as the main function, e.g. you said something like ``` python threading_example.py ``` on the command line. After setting up the special variables, it will execute the `import` statement and load those modules. It will then evaluate the `def` block, creating a function object and creating a variable called `myfunction` that points to the function object. It will then read the `if` statement and see that `__name__` does equal `"__main__"`, so it will execute the block shown there. One of the reasons for doing this is that sometimes you write a module (a `.py` file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves. See [this page](http://ibiblio.org/g2swap/byteofpython/read/module-name.html) for some extra details.
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 gets run automatically - the `main()` function is implicitly all the code at the top level. In this case, the top-level code is an `if` block. `__name__` is a built-in variable which evaluate to the name of the current module. However, if a module is being run directly (as in `myscript.py` above), then `__name__` instead is set to the string `"__main__"`. Thus, you can test whether your script is being run directly or being imported by something else by testing ``` if __name__ == "__main__": ... ``` If that code is being imported into another module, the various function and class definitions will be imported, but the `main()` code won't get run. As a basic example, consider the following two scripts: ``` # file one.py def func(): print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module") # file two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module") ``` Now, if you invoke the interpreter as ``` python one.py ``` The output will be ``` top-level in one.py one.py is being run directly ``` If you run `two.py` instead: ``` python two.py ``` You get ``` top-level in one.py one.py is being imported into another module top-level in two.py func() in one.py two.py is being run directly ``` Thus, when module `one` gets loaded, its `__name__` equals `"one"` instead of `__main__`.
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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: ``` $ python a.py Hello World from b! ``` As you can see, when a module is imported, Python sets `globals()['__name__']` in this module to the module's name. ``` $ python b.py Hello World from __main__! Hello World again from __main__! ``` As you can see, when a file is executed, Python sets `globals()['__name__']` in this file to `"__main__"`.
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 `"__main__"`, and when it'll be imported the `__name__` variable 'll get a different value, most probably the name of the module (`'M'`). This is helpful in running different variants of a modules together, and seperating their specific input & output statements and also if any test-cases. **In short** , use this '`if __name__ == "main"` ' block to prevent (certain) code from being run when the module is imported.
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 you're writing a Python script designed to be used as a module: ``` def do_important(): """This function does something very important""" ``` You *could* test the module by adding this call of the function to the bottom: ``` do_important() ``` and running it (on a command prompt) with something like: ``` ~$ python important.py ``` # The Problem However, if you want to import the module to another script: ``` import important ``` On import, the `do_important` function would be called, so you'd probably comment out your call of the function at the bottom. And then you'll have to remember whether or not you've commented out your test function call. And this extra complexity would mean you're likely to forget, making your development process more troublesome. # A Better Way The `__name__` variable points to the namespace wherever the Python interpreter happens to be at the moment. Inside an imported module, it's the name of that module. But inside the primary module (or an interactive Python session, i.e. the interpreter's Read, Eval, Print Loop, or REPL) you are running everything from its `"__main__"`. So if you check before executing: ``` if __name__ == "__main__": do_important() ``` With the above, your code will only execute when you're running it as the primary module (or intentionally call it from another script). # An Even Better Way There's a Pythonic way to improve on this, though. What if we want to run this business process from outside the module? Also, [Python code can run faster in a function](http://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function) (see the link for how and why); so if we put the code we want to exercise as we develop and test in a function like this and then do our check for `'__main__'` immediately after: ``` def main(): """business logic for when running this module as the primary one!""" setup() foo = do_important() bar = do_even_more_important(foo) for baz in bar: do_super_important(baz) teardown() # Here's our payoff idiom! if __name__ == '__main__': main() ``` We now have a final function for the end of our module that will run if we run the module as the primary module. It will allow the module and its functions and classes to be imported into other scripts (in the most efficient way, if efficiency matters) without running the `main` function, and will also allow the module (and its functions and classes) to be called when running from a different `'__main__'` module, i.e. ``` import important important.main() ``` [This idiom can also be found (deep) in the Python documentation in an explanation of the `__main__` module.](https://docs.python.org/2/library/__main__.html) That text states: > This module represents the (otherwise anonymous) scope in which the > interpreter’s main program executes — commands read either from > standard input, from a script file, or from an interactive prompt. It > is this environment in which the idiomatic “conditional script” stanza > causes a script to run: > > ``` > if __name__ == '__main__': > main() > ```
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 this way, modules can look at their own `__name__` value to determine for themselves how they are being used, whether as support for another program or as the main application executed from the command line. Thus, the following idiom is quite common in Python modules: ``` if __name__ == '__main__': # Do something appropriate here, like calling a # main() function defined elsewhere in this module. main() else: # Do nothing. This module has been imported by another # module that wants to make use of the functions, # classes and other useful bits it has defined. ```
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 whatever Python process you run, as in mycode.py: ``` python mycode.py ``` the otherwise anonymous global namespace is assigned the value of `'__main__'` to its `__name__`. Thus, including [the final lines](https://docs.python.org/library/__main__.html) ``` if __name__ == '__main__': main() ``` * at the end of your mycode.py script, * when it is the primary, entry-point module that is run by a Python process, will cause your script's uniquely defined `main` function to run. Another benefit of using this construct: you can also import your code as a module in another script and then run the main function if and when your program decides: ``` import mycode # ... any amount of other code mycode.main() ```
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 imported and the code is run from there (like when a function in "x.py" is called from y.py).
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() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, 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 of the methods and functions defined in the file, but it does define them.) Before the interpreter executes the source code file though, it defines a few special variables for that file; **\_\_name\_\_** is one of those special variables that Python automatically defines for each source code file. If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special **\_\_name\_\_** variable for this file to have a value **"\_\_main\_\_"**. If this is being imported from another module, **\_\_name\_\_** will be set to that module's name. So, in your example in part: ``` if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) ``` means that the code block: ``` lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) ``` will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of **\_\_name\_\_** will not equal to "**main**" in that particular instance. Hope this helps out.
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 page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project. Thanks in advance. Also, this is my first SO question!
* [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/) + [urllib2](http://docs.python.org/library/urllib2.html) also works quite nicely. * [Scrapy](http://scrapy.org/) looks like an extremely promising project; it's new.
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 page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project. Thanks in advance. Also, this is my first SO question!
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 * Support for extending Scrapy by plugging your own functionality using middlewares, extensions, and pipelines * Wide range of built-in middlewares and extensions for handling of compression, cache, cookies, authentication, user-agent spoofing, robots.txt handling, statistics, crawl depth restriction, etc * Interactive scraping shell console, very useful for developing and debugging * Web management console for monitoring and controlling your bot * Telnet console for low-level access to the Scrapy process Example code to extract information about all torrent files added today in the [mininova](http://www.mininova.org/) torrent site, by using a XPath selector on the HTML returned: ``` class Torrent(ScrapedItem): pass class MininovaSpider(CrawlSpider): domain_name = 'mininova.org' start_urls = ['http://www.mininova.org/today'] rules = [Rule(RegexLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')] def parse_torrent(self, response): x = HtmlXPathSelector(response) torrent = Torrent() torrent.url = response.url torrent.name = x.x("//h1/text()").extract() torrent.description = x.x("//div[@id='description']").extract() torrent.size = x.x("//div[@id='info-left']/p[2]/text()[2]").extract() return [torrent] ```
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 154 > 11:32p Route 154 Once I've grabbed the time and routes then I will update my webpage accordingly. I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?
[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 to figure out what you need.
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 I want that dic to be `a = {'a':100,'b':200,'c':3}` But in my code a[a] doesn't remain 100.It changes to initial value 1. I need an answer ASAP....I m already late...Please help me friends...
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 I want that dic to be `a = {'a':100,'b':200,'c':3}` But in my code a[a] doesn't remain 100.It changes to initial value 1. I need an answer ASAP....I m already late...Please help me friends...
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 I want that dic to be `a = {'a':100,'b':200,'c':3}` But in my code a[a] doesn't remain 100.It changes to initial value 1. I need an answer ASAP....I m already late...Please help me friends...
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 a simple function. You can access the `rememberThis` dictionary using `myFunction.rememberThis`.
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.sourceforge.net/docs/differences.html), most of the problems seem too obscure to bother me. I did notice that: * thread safety is an issue * Unicode support seems to be quite different, which may be a problem for me * mysqldb doesn't work and needs to be replaced with zxJDBC Anything else? Related question: [What are some strategies to write python code that works in CPython, Jython and IronPython](http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i)
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, Oct 31 2008, 13:55:41) >>> 'a' is 'a' True >>> s = 'a' >>> 'a' is s False >>> 'a' == s True >>> intern('a') is intern(s) True ``` Here is the same session on CPython: ``` Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) >>> 'a' is 'a' True >>> s = 'a' >>> 'a' is s True >>> 'a' == s True >>> intern('a') is intern(s) True ``` * os.spawn\* functions are not implemented. Instead use subprocess.call. I was surprised really, as the implementation using subprocess.call would be easy, and I am sure they will accept patches. (I have been doing a similar thing as you, porting an app recently)
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.sourceforge.net/docs/differences.html), most of the problems seem too obscure to bother me. I did notice that: * thread safety is an issue * Unicode support seems to be quite different, which may be a problem for me * mysqldb doesn't work and needs to be replaced with zxJDBC Anything else? Related question: [What are some strategies to write python code that works in CPython, Jython and IronPython](http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i)
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 issues with too many open files. It's better to use the "with open('file') as fp" idiom. * Setting the current working directory (using os.setcwd()) works for Python code, but not for Java code. It emulates the current working directory for everything file-related but can only do so for Jython. * XML parsing will try to validate an external DTD if it's available. This can cause massive slowdowns in XML handling code because the parser will download the DTD over the network. I [reported this issue](http://bugs.jython.org/issue1268), but so far it remains unfixed. * The \_\_ del \_\_ method is invoked very late in Jython code, not immediately after the last reference to the object is deleted. There is an [old list of differences](http://jython.sourceforge.net/archive/21/docs/differences.html), but a recent list is not available.
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 IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great!
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/~piers/python/imaplib.html>
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 prefer python. EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)
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 prefer python. EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)
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(p[3])[0] ```
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 accessible via a function `user.get_profile()` ? Is it really required to explicitly pass the profile into the template every time?
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 accessible via a function `user.get_profile()` ? Is it really required to explicitly pass the profile into the template every time?
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 sure all your users always have profiles it is safe to call from template, otherwise call `get_profile()` from within try-except block in your view and pass it to the template.
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 accessible via a function `user.get_profile()` ? Is it really required to explicitly pass the profile into the template every time?
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 conditions (these can be set to do a variety of things on signaling) * Has positive and negative infinities, as well as NaN (not a number) * Can differentiate between positive and negative 0 * Allows you to set different rounding schemes. * Allows you to set your own min and max values. All in all, it is handy for a [million household uses](http://www.skepticfiles.org/en001/monty16.htm).
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 defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, `modname.itemname`. A specific use of global-in-a-module is described here - [how-do-i-share-global-variables-across-modules](http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm): > The canonical way to share information across modules within a single program is to create a special configuration module (often called config or cfg). Just import the configuration module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example: > > File: config.py ``` x = 0 # Default value of the 'x' configuration setting ``` > File: mod.py ``` import config config.x = 1 ``` > File: main.py ``` import config import mod print config.x ```
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 read value of globvar set_globvar_to_one() print_globvar() # Prints 1 ``` I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the `global` keyword. See other answers if you want to share a global variable across modules.
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 function is defined, it is looked up among global variables. However, if you assign to a new variable not declared as global in the function, it is implicitly declared as local, and it can overshadow any existing global variable with the same name. Also, global variables are useful, contrary to some OOP zealots who claim otherwise - especially for smaller scripts, where OOP is overkill.
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 expecting this to print 42, but instead it prints 5. As has already been mentioned, if you add a '`global`' declaration to `func1()`, then `func2()` will print 42. ``` def func1(): global myGlobal myGlobal = 42 ``` What's going on here is that Python assumes that any name that is *assigned to*, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only *reading* from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope). When you assign 42 to the name `myGlobal`, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is [garbage-collected](http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection) when `func1()` returns; meanwhile, `func2()` can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of `myGlobal` inside `func1()` before you assign to it, you'd get an `UnboundLocalError`, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the '`global`' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally. (I believe that this behavior originated largely through an optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)
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 specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases. You *could* have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program.
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 global. ``` >>> import dis >>> def foo(): ... global bar ... baz = 5 ... print bar ... print baz ... print quux ... >>> dis.disassemble(foo.func_code) 3 0 LOAD_CONST 1 (5) 3 STORE_FAST 0 (baz) 4 6 LOAD_GLOBAL 0 (bar) 9 PRINT_ITEM 10 PRINT_NEWLINE 5 11 LOAD_FAST 0 (baz) 14 PRINT_ITEM 15 PRINT_NEWLINE 6 16 LOAD_GLOBAL 1 (quux) 19 PRINT_ITEM 20 PRINT_NEWLINE 21 LOAD_CONST 0 (None) 24 RETURN_VALUE >>> ``` See how baz, which appears on the left side of an assignment in `foo()`, is the only `LOAD_FAST` variable.
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): oldValue = get() set(random.randint(0, 100)) sys.stderr.write(' '.join([str(os.getpid()), str(a), 'old:', str(oldValue), 'new:', str(get()), '\n'])) def get(): global globalVariable return globalVariable globalVariable = -1 def set(v): global globalVariable globalVariable = v print get() set(-2) print get() processPool = multiprocessing.Pool(5) results = processPool.map(worker, range(15)) ``` **Output:** ``` 27094 0 old: -2 new: 2 27094 1 old: 2 new: 95 27094 2 old: 95 new: 20 27094 3 old: 20 new: 54 27098 4 old: -2 new: 80 27098 6 old: 80 new: 62 27095 5 old: -2 new: 100 27094 7 old: 54 new: 23 27098 8 old: 62 new: 67 27098 10 old: 67 new: 22 27098 11 old: 22 new: 85 27095 9 old: 100 new: 32 27094 12 old: 23 new: 65 27098 13 old: 85 new: 60 27095 14 old: 32 new: 71 ```
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 TestPy def main(): atest = TestPy atest.five(5,8) print(atest.isTheNumber()) if __name__ == '__main__': main() ``` This simple code works just like that, and it will execute. I hope it helps.
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 value inside the function, the variable is > implicitly local, and you need to explicitly declare it as ‘global’. > > Though a bit surprising at first, a moment’s consideration explains > this. On one hand, requiring global for assigned variables provides a > bar against unintended side-effects. On the other hand, if global was > required for all global references, you’d be using global all the > time. You’d have to declare as global every reference to a built-in > function or to a component of an imported module. This clutter would > defeat the usefulness of the global declaration for identifying > side-effects. Source: *[What are the rules for local and global variables in Python?](https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python)*.
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(): #We are NOT telling to explicitly use the global version, so we are creating a local variable var = "local version from printLocalText fun" print "var from printLocalText: " + var printGlobalText() printLocalText() """ Output Result: var from printGlobalText: global from printGlobalText fun. var from printLocalText: local version from printLocalText [Finished in 0.1s] """ ```
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 scope global_variable = 'Foo' ``` Writing a function does not actually run its code. So we call the `create_global_variable` function: ``` >>> create_global_variable() ``` ## Using globals without modification You can just use it, so long as you don't expect to change which object it points to: For example, ``` def use_global_variable(): return global_variable + '!!!' ``` and now we can use the global variable: ``` >>> use_global_variable() 'Foo!!!' ``` ## Modification of the global variable from inside a function To point the global variable at a different object, you are required to use the global keyword again: ``` def change_global_variable(): global global_variable global_variable = 'Bar' ``` Note that after writing this function, the code actually changing it has still not run: ``` >>> use_global_variable() 'Foo!!!' ``` So after calling the function: ``` >>> change_global_variable() ``` we can see that the global variable has been changed. The `global_variable` name now points to `'Bar'`: ``` >>> use_global_variable() 'Bar!!!' ``` Note that "global" in Python is not truly global - it's only global to the module level. So it is only available to functions written in the modules in which it is global. Functions remember the module in which they are written, so when they are exported into other modules, they still look in the module in which they were created to find global variables. # Local variables with the same name If you create a local variable with the same name, it will overshadow a global variable: ``` def use_local_with_same_name_as_global(): # bad name for a local variable, though. global_variable = 'Baz' return global_variable + '!!!' >>> use_local_with_same_name_as_global() 'Baz!!!' ``` But using that misnamed local variable does not change the global variable: ``` >>> use_global_variable() 'Bar!!!' ``` Note that you should avoid using the local variables with the same names as globals unless you know precisely what you are doing and have a very good reason to do so. I have not yet encountered such a reason.
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 rely on an environment setup done in **main**. Looking at <http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest> - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed. How can I do the setup and cleanup once for all the tests in my TestSuite? The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.
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 the cleanup, use: ``` @classmethod def tearDownClass(cls): # ... ``` See also the unittest standard library [documentation on setUpClass and tearDownClass classmethods](http://docs.python.org/py3k/library/unittest.html#setupclass-and-teardownclass).
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 (Sequence in Sequence): ``` >>> seq_in_seq([5,6], [4,'a',3,5,6]) 3 >>> seq_in_seq([5,7], [4,'a',3,5,6]) -1 # or None, or whatever ``` So far, I just rely on brute force and it seems slow, ugly, and clumsy.
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 in a given sequence, and should be used as an iterator: ``` >>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s 3 >>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s (nothing) ```
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://jdhardy.blogspot.com/2008/12/solving-zlib-problem-ironpythonzlib.html) which discusses the absence of zlib for IronPython; hence, no easyinstall. Jeff reimplemented zlib based on ComponentAce's zlib.net. And finally, in [easy\_install on IronPython, Part Deux](http://jdhardy.blogspot.com/2008/12/easyinstall-on-ironpython-part-deux.html) Jeff discusses some final tweaks that are needed before easy\_install can be used with IronPython.
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: parser.error('--foo option is required') print "Your foo is %s." % options.foo return 0 if __name__ == '__main__': sys.exit(main()) ``` With code that looks like this: ``` @patch('optparse.OptionParser') def test_main_with_missing_p4clientsdir_option(self, mock_optionparser): # # setup # optionparser_mock = Mock() mock_optionparser.return_value = optionparser_mock options_stub = Mock() options_stub.foo = None optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments) def parser_error_mock(message): self.assertEquals(message, '--foo option is required') sys.exit(2) optionparser_mock.error = parser_error_mock # # exercise & verify # self.assertEquals(sut.main(), 2) ``` I'm using [Michael Foord's Mock](http://www.voidspace.org.uk/python/mock.html), and nose to run the tests. When I run the test, I get: ``` File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock sys.exit(2) SystemExit: 2 ---------------------------------------------------------------------- Ran 1 test in 0.012s FAILED (errors=1) ``` The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test. I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser\_error\_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution? **Update**: [df](http://stackoverflow.com/users/3002/df)'s answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)". Which means the test passes whatever the number is in the sys.exit() in parser\_error\_mock(). Is there any way to test for the exit code? BTW, the test is more robust if I add: ``` self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})]) ``` at the end. **Update 2**: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with: ``` try: sut.main() except SystemExit, e: self.assertEquals(type(e), type(SystemExit())) self.assertEquals(e.code, 2) except Exception, e: self.fail('unexpected exception: %s' % e) else: self.fail('SystemExit exception expected') ```
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 best learning experience I would learn each techonology independently but I don't have the time. :) So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for: 1. Documentation of API 2. Tutorials 3. Tools 4. Supportive Community 5. Completness of Cocoa API avaialble through the bridge Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.
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 either PyObjC or RubyCocoa.
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 best learning experience I would learn each techonology independently but I don't have the time. :) So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for: 1. Documentation of API 2. Tutorials 3. Tools 4. Supportive Community 5. Completness of Cocoa API avaialble through the bridge Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application.
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 modify classes at run time are required to implement Cocoa technologies such as Distributed Objects and bindings. Although these features are available in other dynamic languages such as Ruby and Python, there is enough of a mismatch in the language models that you will have to at least understand Objective-C to understand Cocoa. I suggest you take a look at this previous question for further discussion: [Do I have to learn Objective-C for professional Mac Development?](http://stackoverflow.com/questions/272660/do-i-have-to-learn-objective-c-for-professional-mac-development) Fortunately, Objective-C is very easy to learn. I often tell people it will take them a day to learn Objective-C coming from C/C++/Java or LISP, Scheme, or any of the 'newer' dynamic languages such as Ruby and Python. In addition to expanding your mind a bit, you'll learn to at least read the code that is used in virtually all of the Cocoa documentation and examples. As for Ruby vs. Python, the bridge capabilities are very similar. In fact, they both use Apple's [BridgeSupport](http://bridgesupport.macosforge.org/trac/) (shipped with Leopard) to provide the bridge description. Both are supported by Apple and ship with Leopard. It's a matter of personal taste which language you prefer. If you choose Ruby, I suggest you give [MacRuby](http://www.macruby.org/trac/wiki/MacRuby) a look. It's definitely the future of Ruby on OS X, as it reimplements the Ruby runtime on top of the Objective-C run time. This provides some nice performance and conceptual advantages (including integration with the Objective-C garbage collection system, a feature currently lacking in PyObjC which uses the native python gc). MacRuby also includes a custom parser that makes the syntax of bridged objective-c methods a little nicer. The downside of MacRuby is that it's not quite ready for production-level use at the time of this writing (June 2009). Since it sounds like this is a learning project for you, that's probably not an issue.
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 easily if you don’t like the > auto-generated slug).
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://stackoverflow.com/questions/427102/different-slug-same-content) (on this site at least)
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> <content> A silly comedy movie </content> <slug> the-46-year-old-virgin </slug> ``` Now let's pretend that we have a Django model such as: ``` class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=1000) slug = models.SlugField(max_length=40) ``` How would you reference this object with a URL, with a meaningful name? You could use Article.id so the URL would look like this: ``` www.example.com/article/23 ``` Or, you could reference the title like so: ``` www.example.com/article/The 46 Year Old Virgin ``` Problem is, spaces aren't valid in URLs, they need to be replaced by `%20` which is ugly, making it the following: ``` www.example.com/article/The%2046%20Year%20Old%20Virgin ``` That's not solving our meaningful URL. Wouldn't this be better: ``` www.example.com/article/the-46-year-old-virgin ``` That's a slug. `the-46-year-old-virgin`. All letters are downcased and spaces are replaced by hyphens `-`. See the URL of this very webpage for an example!
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 fixed those errors in the 'russia-cuts-europe-gas' story?". Django uses it as part of the URL to locate the story, an example being `www.mysite.com/archives/russia-cuts-europe-gas`.
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 career there, and all the way to the top. (Not anymore) Typographs had to compose the text of the article in a backward manner with lead caracters stacked in a wise. So at printing time the letters would be straight on the paper. All typographs could read the newspaper mirrored as fast as the printed one.Therefore the slugs, (like snails) also the slow stories (the lasts to be fixed) were many on the bench waiting, solely identified by their fist letters, mostly the whole title generaly more readable. Some "hot" news were waiting there on the bench, for possible last minute correction, (Evening paper) before last assembly and definitive printing. Django emerged from the offices of the Lawrence journal in Kansas. Where probably some printing jargon still lingers. **A-django-enthousiast-&-friendly-old-slug-boy-from-France.**
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 its source code.
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_ADD 7 STORE_FAST 2 (a) 4 10 LOAD_FAST 2 (a) 13 RETURN_VALUE ```
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 interactively. It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code. ``` >>> from dill.source import getsource >>> >>> def add(x,y): ... return x+y ... >>> squared = lambda x:x**2 >>> >>> print getsource(add) def add(x,y): return x+y >>> print getsource(squared) squared = lambda x:x**2 >>> >>> class Foo(object): ... def bar(self, x): ... return x*x+x ... >>> f = Foo() >>> >>> print getsource(f.bar) def bar(self, x): return x*x+x >>> ```
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 plain `python`. It should be fine in both, however, when importing code from source files.
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 = models.ForeignKey('self') ``` What way is preferred? What drawbacks have each solution?
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 code, linked list are used to get better insert performance compared to arrays (no need to move all elements around). In your database, updating all elements is not that complicated in only 2 queries : ``` UPDATE item.order = item.order + 1 FROM item WHERE order > 3 INSERT INTO item (order, ...) VALUES (3, ...) ``` I remember seeing a reuseable app that implemented all that and a nice admin interface, but I cant find it right now ... To summarize, definitly use solution #1 and stay away from solution #2 unless you have a very very good reason not to !
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) ``` I haven't been able to find the spec on how the document should be posted to the SOAP Server. urllib is not a necessary requirement.
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", "\"\"") webservice.endheaders() webservice.send(f) ```
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 want the substitution to take place. (Otherwise, I'll end up with **.min.min.js**) How can I accomplish this by using regular expression? PS: This is not homework. If you're curious what this is for: this is for a small python script to do mass compress of JavaScript files in a directory.
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 string in strings] ``` Output: ``` [('foofo', '21'), ('bar', '432'), ('foobar', '12345')] ```
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.compile(r"\'(.*?)(?<!\\)\'") match = regexc.search(r""" Example: 'Foo \' Bar' End. """) print match.groups() # I want ("Foo \' Bar") to be printed above ``` After looking at this, there is a simple problem that the escape character being used, "`\`", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length: ``` # ... re.compile(r"\'(.*?)(?<!\\(\\\\)*)\'") # ... ``` Any regex gurus able to tackle this problem? Thanks.
## 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://rads.stackoverflow.com/amzn/click/0596528124 "By Jeffrey Friedl. Best book on Regex - ever!"), (which covers this specific problem in great detail - *highly* recommended). First let's look at the sub-expression to match a single quoted string which may contain escaped single quotes. If you are going to allow escaped single quotes, you had better at least allow escaped-escapes as well (which is what Douglas Leeder's answer does). But as long as you're at it, its just as easy to allow escaped-anything-else. With these requirements. MizardX is the only one who got the expression right. Here it is in both short and long format (and I've taken the liberty to write this in `VERBOSE` mode, with lots of descriptive comments - which you should *always* do for non-trivial regexes): ``` # MizardX's correct regex to match single quoted string: re_sq_short = r"'((?:\\.|[^\\'])*)'" re_sq_long = r""" ' # Literal opening quote ( # Capture group $1: Contents. (?: # Group for contents alternatives \\. # Either escaped anything | [^\\'] # or one non-quote, non-escape. )* # Zero or more contents alternatives. ) # End $1: Contents. ' """ ``` This works and correctly matches all the following string test cases: ``` text01 = r"out1 'escaped-escape: \\ ' out2" test02 = r"out1 'escaped-quote: \' ' out2" test03 = r"out1 'escaped-anything: \X ' out2" test04 = r"out1 'two escaped escapes: \\\\ ' out2" test05 = r"out1 'escaped-quote at end: \'' out2" test06 = r"out1 'escaped-escape at end: \\' out2" ``` Ok, now lets begin to improve on this. First, the order of the alternatives makes a difference and one should always put the most likely alternative first. In this case, non escaped characters are more likely than escaped ones, so reversing the order will improve the regex's efficiency slightly like so: ``` # Better regex to match single quoted string: re_sq_short = r"'((?:[^\\']|\\.)*)'" re_sq_long = r""" ' # Literal opening quote ( # $1: Contents. (?: # Group for contents alternatives [^\\'] # Either a non-quote, non-escape, | \\. # or an escaped anything. )* # Zero or more contents alternatives. ) # End $1: Contents. ' """ ``` ## "Unrolling-the-Loop": This is a little better, but can be further improved (significantly) by applying Jeffrey Friedl's *"unrolling-the-loop"* efficiency technique (from [MRE3](http://rads.stackoverflow.com/amzn/click/0596528124 "Mastering Regular Expressions (3rd Edition)")). The above regex is not optimal because it must painstakingly apply the star quantifier to the non-capture group of two alternatives, each of which consume only one or two characters at a time. This alternation can be eliminated entirely by recognizing that a similar pattern is repeated over and over, and that an equivalent expression can be crafted to do the same thing without alternation. Here is an optimized expression to match a single quoted string and capture its contents into group `$1`: ``` # Better regex to match single quoted string: re_sq_short = r"'([^'\\]*(?:\\.[^'\\]*)*)'" re_sq_long = r""" ' # Literal opening quote ( # $1: Contents. [^'\\]* # {normal*} Zero or more non-', non-escapes. (?: # Group for {(special normal*)*} construct. \\. # {special} Escaped anything. [^'\\]* # More {normal*}. )* # Finish up {(special normal*)*} construct. ) # End $1: Contents. ' """ ``` This expression gobbles up all non-quote, non-backslashes (the vast majority of most strings), in one "gulp", which drastically reduces the amount of work that the regex engine must perform. How much better you ask? Well, I entered each of the regexes presented from this question into [RegexBuddy](http://www.regexbuddy.com/ "An excellent tool for crafting and debugging regular expressions") and measured how many steps it took the regex engine to complete a match on the following string (which all solutions correctly match): `'This is an example string which contains one \'internally quoted\' string.'` Here are the benchmark results on the above test string: ``` r""" AUTHOR SINGLE-QUOTE REGEX STEPS TO: MATCH NON-MATCH Evan Fosmark '(.*?)(?<!\\)' 374 376 Douglas Leeder '(([^\\']|\\'|\\\\)*)' 154 444 cletus/PEZ '((?:\\'|[^'])*)(?<!\\)' 223 527 MizardX '((?:\\.|[^\\'])*)' 221 369 MizardX(improved) '((?:[^\\']|\\.)*)' 153 369 Jeffrey Friedl '([^\\']*(?:\\.[^\\']*)*)' 13 19 """ ``` These steps are the number of steps required to match the test string using the RegexBuddy debugger function. The "NON-MATCH" column is the number of steps required to declare match failure when the closing quote is removed from the test string. As you can see, the difference is significant for both the matching and non-matching cases. Note also that these efficiency improvements are only applicable to a NFA engine which uses backtracking (i.e. Perl, PHP, Java, Python, Javascript, .NET, Ruby and most others.) A DFA engine will not see any performance boost by this technique (See: [Regular Expression Matching Can Be Simple And Fast](http://swtch.com/~rsc/regexp/regexp1.html)). ## On to the complete solution: The goal of the original question (my interpretation), is to pick out single quoted sub-strings (which may contain escaped quotes) from a larger string. If it is known that the text outside the quoted sub-strings will never contain escaped-single-quotes, the regex above will do the job. However, to correctly match single-quoted sub-strings within a sea of text swimming with escaped-quotes and escaped-escapes and escaped-anything-elses, (which is my interpretation of what the author is after), requires parsing from the beginning of the string No, (this is what I originally thought), but it doesn't - this can be achieved using MizardX's very clever `(?<!\\)(?:\\\\)*` expression. Here are some test strings to exercise the various solutions: ``` text01 = r"out1 'escaped-escape: \\ ' out2" test02 = r"out1 'escaped-quote: \' ' out2" test03 = r"out1 'escaped-anything: \X ' out2" test04 = r"out1 'two escaped escapes: \\\\ ' out2" test05 = r"out1 'escaped-quote at end: \'' out2" test06 = r"out1 'escaped-escape at end: \\' out2" test07 = r"out1 'str1' out2 'str2' out2" test08 = r"out1 \' 'str1' out2 'str2' out2" test09 = r"out1 \\\' 'str1' out2 'str2' out2" test10 = r"out1 \\ 'str1' out2 'str2' out2" test11 = r"out1 \\\\ 'str1' out2 'str2' out2" test12 = r"out1 \\'str1' out2 'str2' out2" test13 = r"out1 \\\\'str1' out2 'str2' out2" test14 = r"out1 'str1''str2''str3' out2" ``` Given this test data let's see how the various solutions fare ('p'==pass, 'XX'==fail): ``` r""" AUTHOR/REGEX 01 02 03 04 05 06 07 08 09 10 11 12 13 14 Douglas Leeder p p XX p p p p p p p p XX XX XX r"(?:^|[^\\])'(([^\\']|\\'|\\\\)*)'" cletus/PEZ p p p p p XX p p p p p XX XX XX r"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'" MizardX p p p p p p p p p p p p p p r"(?<!\\)(?:\\\\)*'((?:\\.|[^\\'])*)'" ridgerunner p p p p p p p p p p p p p p r"(?<!\\)(?:\\\\)*'([^'\\]*(?:\\.[^'\\]*)*)'" """ ``` ## A working test script: ``` import re data_list = [ r"out1 'escaped-escape: \\ ' out2", r"out1 'escaped-quote: \' ' out2", r"out1 'escaped-anything: \X ' out2", r"out1 'two escaped escapes: \\\\ ' out2", r"out1 'escaped-quote at end: \'' out2", r"out1 'escaped-escape at end: \\' out2", r"out1 'str1' out2 'str2' out2", r"out1 \' 'str1' out2 'str2' out2", r"out1 \\\' 'str1' out2 'str2' out2", r"out1 \\ 'str1' out2 'str2' out2", r"out1 \\\\ 'str1' out2 'str2' out2", r"out1 \\'str1' out2 'str2' out2", r"out1 \\\\'str1' out2 'str2' out2", r"out1 'str1''str2''str3' out2", ] regex = re.compile( r"""(?<!\\)(?:\\\\)*'([^'\\]*(?:\\.[^'\\]*)*)'""", re.DOTALL) data_cnt = 0 for data in data_list: data_cnt += 1 print ("\nData string %d" % (data_cnt)) m_cnt = 0 for match in regex.finditer(data): m_cnt += 1 if (match.group(1)): print(" quoted sub-string%3d = \"%s\"" % (m_cnt, match.group(1))) ``` # Phew! p.s. Thanks to MizardX for the very cool `(?<!\\)(?:\\\\)*` expression. Learn something new every day!
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 looking for two different answers: 1. What's the library solution for parsing HTML links. [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) seems to be a good solution (thanks, `Igal Serban` and `cletus`!) 2. Can a link be defined using a regex?
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 looking for two different answers: 1. What's the library solution for parsing HTML links. [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) seems to be a good solution (thanks, `Igal Serban` and `cletus`!) 2. Can a link be defined using a regex?
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, HTML links ought to be well-defined, but the HTML you actually encounter is very unlikely to be standard. The beauty of BeautifulSoup is that it uses browser-like heuristics to try to parse the non-standard, malformed HTML that you are likely to actually come across. If you are certain to be working on standard XHTML, you can use (much) faster XML parsers like expat. Regex, for the reasons above (the parser must maintain state, and regex can't do that) will never be a general solution.
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 ``` tell application "Finder" set desktop picture to POSIX file "/your/filename.jpg" end tell ``` You can run it from the command line using [`osascript`](http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/ManPages/man1/osascript.1.html), or from Python using something like ``` import subprocess SCRIPT = """/usr/bin/osascript<<END tell application "Finder" set desktop picture to POSIX file "%s" end tell END""" def set_desktop_background(filename): subprocess.Popen(SCRIPT%filename, shell=True) ```
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.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}' chown joeuser /Users/joeuser/Library/Preferences/com.apple.desktop.plist ``` You will of course want to replace the image filename and user name. The new setting will take effect when the Dock starts up -- either at login, or, when you ``` killall Dock ``` [Based on [a posting elsewhere](http://forums.macrumors.com/showpost.php?p=7237192&postcount=18), and based on information from [Matt Miller's answer](http://stackoverflow.com/questions/431205/how-can-i-programatically-change-the-background-in-mac-os-x/431273#431273).]
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.ArgumentParser(description='Set desktop wallpaper.') parser.add_argument('file', type=file, help='File to use as wallpaper.') args = parser.parse_args() f = args.file se = app('System Events') desktops = se.desktops.display_name.get() for d in desktops: desk = se.desktops[its.display_name == d] desk.picture.set(mactypes.File(f.name)) __main__() ```
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 old path and not the new one. 2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in [his answer](http://stackoverflow.com/questions/431684/how-do-i-cd-in-python/13197763#13197763). Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use `os.chdir()` to change the CWD of the calling process.
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_directory): # code in here occurs within the directory # code here is in the original directory ``` *UPDATE* If you prefer to roll your own: ``` import os from contextlib import contextmanager @contextmanager def working_directory(directory): owd = os.getcwd() try: os.chdir(directory) yield directory finally: os.chdir(owd) ```
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 for changing the current working directory""" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath) ``` Or try the [more concise equivalent(below)](http://stackoverflow.com/a/24176022/263998), using [ContextManager](https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager). ### Example ``` import subprocess # just to call an arbitrary command e.g. 'ls' # enter the directory like this: with cd("~/Library"): # we are in ~/Library subprocess.call("ls") # outside the context manager we are back wherever we started. ```
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 return pipes.quote(s) def put_text_back_into_terminal_input_buffer(text): # use of this means that it only works in an interactive session # (and if the user types while it runs they could insert characters between the characters in 'text'!) import fcntl, termios for c in text: fcntl.ioctl(1, termios.TIOCSTI, c) def change_parent_process_directory(dest): # the horror put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n") ```
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 after an exception is thrown: ``` os.chdir('/home') with cd('/tmp'): # ... raise Exception("There's no place like home.") # Directory is now back to '/home'. ```
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 the same.
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 ```