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
Good language to develop a game server in?
392,624
11
2008-12-25T08:25:54Z
392,627
19
2008-12-25T08:30:16Z
[ "c#", "java", "python", "networking" ]
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out). I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development? Please help me and my picky self arrive on a solution. UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?
I hate to say it, and I know I'm risking a down mod here, but it doesn't sound like there's a language out there for you. All programming languages have their quirks and programmers simply have to adapt to them. It's completely possible to write a working server in Python without classes (eliminating the "self" variable class references) and likewise just as easy to write C++ with clean syntax. If you're looking to deploy cross-platform and want to develop cross-platform as well, your best bet would probably be Java. It shorter development cycles than compiled languages like C and C++, but is higher performance (arguable, but I've always been anti-Java =P) than interpreted languages like Python and Perl and you don't have to work with unofficial implementations like Mono that may from time to time not support all of a language's features.
Good language to develop a game server in?
392,624
11
2008-12-25T08:25:54Z
392,650
7
2008-12-25T08:55:56Z
[ "c#", "java", "python", "networking" ]
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out). I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development? Please help me and my picky self arrive on a solution. UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?
What kind of performance do you need? twisted is great for servers that need lots of concurrency, as is erlang. Either supports massive concurrency easily and has facilities for distributed computing. If you want to span more than one core in a python app, do the same thing you'd do if you wanted to span more than one machine — run more than one process.
Good language to develop a game server in?
392,624
11
2008-12-25T08:25:54Z
392,672
7
2008-12-25T09:23:36Z
[ "c#", "java", "python", "networking" ]
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out). I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development? Please help me and my picky self arrive on a solution. UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?
Speaking of pure performance, if you can run Java 6 you get about 1:1 performance when compared to optimized C++ (special cases notwithstanding, sometimes Java is faster, sometimes C++), the only problem you will have is of course stuff like database libraries, interconnectivity, scalability and such. I believe there's a variety of good to great solutions available to each of these problems but you won't find one language which would solve everything for you so I have to give you the age old advice: Choose the language you like and use that one. Oh, you're still reading this? :) Well, here's some extra pointers. * [EVE Online](http://www.eve-online.com/) uses Python for its client and server side code and it's both bug-ridden and laggy as something I don't think I should write here so that'd be an example of how Python can be extended to (poorly) serve vast amounts of users. * While Java has some good to great solutions to various related problems, it's really not the best language out there for vast amount of users; it doesn't scale well to extremes without tuning. However there's multi-VM solutions to this which somewhat fix the issue, for example [Terracotta](http://www.terracotta.org/) is said to do the job well. * While C++ is rather cumbersome, it allows for such a low-level interaction with the system that you may actually find yourself doing things you thought you couldn't do. I'm thinking of something like dynamic per-core microclustering of runtime code blocks for "filling" every possible clock cycle of the processor as efficiently as possible for maximum performance and things like that. * Mono is far behind the .NET VM/equivalent on Windows platforms so you wouldn't be able to use the latest and fanciest features of C#. However Windows XP (x64) OEM licenses are so laughably cheap at the moment that with small investment you could get a bunch of those and you could then run your code on the platform it was meant to be. And don't fall into the Linux hype, Linux is your saviour only if you really know how to use it and especially XP is pretty damn fast and stable nowadays.
Good language to develop a game server in?
392,624
11
2008-12-25T08:25:54Z
392,814
16
2008-12-25T13:50:59Z
[ "c#", "java", "python", "networking" ]
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out). I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development? Please help me and my picky self arrive on a solution. UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?
Erlang is a language which is designed around concurrency and distribution over several servers, which is perfect for server software. Some links about Erlang and game-servers: <http://www.devmaster.net/articles/mmo-scalable-server/> <http://www.erlang-consulting.com/euc2005/mmog/mmog_in_erlang.htm> I'm thinking of writing a game-server in Erlang myself.
Good language to develop a game server in?
392,624
11
2008-12-25T08:25:54Z
392,911
13
2008-12-25T15:57:19Z
[ "c#", "java", "python", "networking" ]
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out). I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development? Please help me and my picky self arrive on a solution. UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?
I might be going slightly off-topic here, but the topic interests me as I have (hobby-wise) worked on quite a few game servers (MMORPG servers) - on others' code as well as mine. There is literature out there that will be of interest to you, drop me a note if you want some references. One thing that strikes me in your question is the want to serve a thousand users off a multithreaded application. From my humble experience, that does not work too well. :-) When you serve thousands of users you want a design that is as modular as possible, because one of your primary goals will be to keep the service as a whole up and running. Game servers tend to be rather complex, so there will be quite a few show-stopping bugs. Don't make your life miserable with a single point of failure (one application!). Instead, try to build multiple processes that can run on a multitude of hosts. My humble suggestion is the following: * Make them independent, so a failing process will be irrelevant to the service. * Make them small, so that the different parts of the service and how they interact are easy to grasp. * Don't let users communicate with the gamelogic OR DB directly. Write a proxy - network stacks can and will show odd behaviour on different architectures when you have a multitude of users. Also make sure that you can later "clean"/filter what the proxies forward. * Have a process that will only monitor other processes to see if they are still working properly, with the ability to restart parts. * Make them distributable. Coordinate processes via TCP from the start or you will run into scalability problems. * If you have large landscapes, consider means to dynamically divide load by dividing servers by geography. Don't have every backend process hold all the data in memory. I have ported a few such engines written in C++ and C# for hosts operating on Linux, FreeBSD and also Solaris (on an old UltraSparc IIi - yes, mono still runs there :). From my experience, C# is well fast enough, considering on what ancient hardware it operates on that sparc machine. The industry (as far as I know) tends to use a lot of C++ for the serving work and embeds scripting languages for the actual game logic. Ah, written too much already - way cool topic.
How to make a color from a number
392,728
4
2008-12-25T10:56:00Z
392,732
10
2008-12-25T10:58:37Z
[ "python", "colors" ]
I have a function that returns a float from 0 to 255. I would like to make a gradient in red color from this, but I need a string in "#FFFFFF" format. Is there a function for that?
You could use: ``` "#%02X0000" % x ```
Length of generator output
393,053
81
2008-12-25T18:50:18Z
393,059
26
2008-12-25T18:53:39Z
[ "python", "generator", "iterable" ]
Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like: ``` def iterlen(x): n = 0 try: while True: next(x) n += 1 except StopIteration: pass return n ``` But I can't get rid of a feeling that I'm reimplementing a bicycle. (While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though). P.S.: concerning the first answers - yes, something like `len(list(x))` would work too, but that drastically increases the usage of memory. P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.
There isn't one because you can't do it in the general case - what if you have a lazy infinite generator? For example: ``` def fib(): a, b = 0, 1 while True: a, b = b, a + b yield a ``` This never terminates but will generate the Fibonacci numbers. You can get as many Fibanacci numbers as you want by calling `next()`. If you really need to know the number of items there are, then you can't iterate through them linearly one time anyways, so just use a different data structure such as a regular list.
Length of generator output
393,053
81
2008-12-25T18:50:18Z
393,134
7
2008-12-25T19:55:48Z
[ "python", "generator", "iterable" ]
Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like: ``` def iterlen(x): n = 0 try: while True: next(x) n += 1 except StopIteration: pass return n ``` But I can't get rid of a feeling that I'm reimplementing a bicycle. (While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though). P.S.: concerning the first answers - yes, something like `len(list(x))` would work too, but that drastically increases the usage of memory. P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.
You can use enumerate() to loop through the generated data stream, then return the last number -- the number of items. I tried to use itertools.count() with itertools.izip() but no luck. This is the best/shortest answer I've come up with: ``` #!/usr/bin/python import itertools def func(): for i in 'yummy beer': yield i def icount(ifunc): size = -1 # for the case of an empty iterator for size, _ in enumerate(ifunc()): pass return size + 1 print list(func()) print 'icount', icount(func) # ['y', 'u', 'm', 'm', 'y', ' ', 'b', 'e', 'e', 'r'] # icount 10 ``` Kamil Kisiel's solution is way better: ``` def count_iterable(i): return sum(1 for e in i) ```
Length of generator output
393,053
81
2008-12-25T18:50:18Z
7,223,557
161
2011-08-28T20:04:50Z
[ "python", "generator", "iterable" ]
Python provides a nice method for getting length of an eager iterable, `len(x)` that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like: ``` def iterlen(x): n = 0 try: while True: next(x) n += 1 except StopIteration: pass return n ``` But I can't get rid of a feeling that I'm reimplementing a bicycle. (While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though). P.S.: concerning the first answers - yes, something like `len(list(x))` would work too, but that drastically increases the usage of memory. P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.
The easiest way is probably just `sum(1 for _ in gen)` where gen is your generator.
Python sqlite3 and concurrency
393,554
54
2008-12-26T06:51:54Z
393,576
34
2008-12-26T07:10:39Z
[ "python", "sqlite" ]
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line: ``` conn = sqlite3.connect("mydatabase.db") ``` * If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it. * If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread. Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?
You can use consumer-producer pattern. For example you can create queue that is shared between threads. First thread that fetches data from the web enqueues this data in the shared queue. Another thread that owns database connection dequeues data from the queue and passes it to the database.
Python sqlite3 and concurrency
393,554
54
2008-12-26T06:51:54Z
393,984
10
2008-12-26T16:51:24Z
[ "python", "sqlite" ]
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line: ``` conn = sqlite3.connect("mydatabase.db") ``` * If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it. * If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread. Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?
Switch to [multiprocessing](http://docs.python.org/library/multiprocessing.html). It is much better, scales well, can go beyond the use of multiple cores by using multiple CPUs, and the interface is the same as using python threading module. Or, as Ali suggested, just use [SQLAlchemy's thread pooling mechanism](http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/pooling.html#sqlalchemy.pool.SingletonThreadPool). It will handle everything for you automatically and has many extra features, just to quote some of them: 1. SQLAlchemy includes dialects for SQLite, Postgres, MySQL, Oracle, MS-SQL, Firebird, MaxDB, MS Access, Sybase and Informix; IBM has also released a DB2 driver. So you don't have to rewrite your application if you decide to move away from SQLite. 2. The Unit Of Work system, a central part of SQLAlchemy's Object Relational Mapper (ORM), organizes pending create/insert/update/delete operations into queues and flushes them all in one batch. To accomplish this it performs a topological "dependency sort" of all modified items in the queue so as to honor foreign key constraints, and groups redundant statements together where they can sometimes be batched even further. This produces the maxiumum efficiency and transaction safety, and minimizes chances of deadlocks.
Python sqlite3 and concurrency
393,554
54
2008-12-26T06:51:54Z
394,331
13
2008-12-26T21:59:14Z
[ "python", "sqlite" ]
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line: ``` conn = sqlite3.connect("mydatabase.db") ``` * If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it. * If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread. Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?
You shouldn't be using threads at all for this. This is a trivial task for [twisted](http://twistedmatrix.com/) and that would likely take you significantly further anyway. Use only one thread, and have the completion of the request trigger an event to do the write. twisted will take care of the scheduling, callbacks, etc... for you. It'll hand you the entire result as a string, or you can run it through a stream-processor (I have a [twitter API](https://github.com/dustin/twitty-twister) and a [friendfeed API](https://github.com/dustin/twisted-friends) that both fire off events to callers as results are still being downloaded). Depending on what you're doing with your data, you could just dump the full result into sqlite as it's complete, cook it and dump it, or cook it while it's being read and dump it at the end. I have a very simple application that does something close to what you're wanting on github. I call it [pfetch](https://github.com/dustin/pfetch) (parallel fetch). It grabs various pages on a schedule, streams the results to a file, and optionally runs a script upon successful completion of each one. It also does some fancy stuff like conditional GETs, but still could be a good base for whatever you're doing.
Python sqlite3 and concurrency
393,554
54
2008-12-26T06:51:54Z
2,578,401
12
2010-04-05T12:41:29Z
[ "python", "sqlite" ]
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line: ``` conn = sqlite3.connect("mydatabase.db") ``` * If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it. * If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread. Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?
The following found on [mail.python.org.pipermail.1239789](http://mail.python.org/pipermail/python-list/2010-March/1239789.html) I have found the solution. I don't know why python documentation has not a single word about this option. So we have to add a new keyword argument to connection function and we will be able to create cursors out of it in different thread. So use: ``` sqlite.connect(":memory:", check_same_thread = False) ``` works out perfectly for me. Of course from now on I need to take care of safe multithreading access to the db. Anyway thx all for trying to help.
Python sqlite3 and concurrency
393,554
54
2008-12-26T06:51:54Z
2,894,830
115
2010-05-24T05:03:46Z
[ "python", "sqlite" ]
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line: ``` conn = sqlite3.connect("mydatabase.db") ``` * If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it. * If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread. Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?
Contrary to popular belief, newer versions of sqlite3 **do** support access from multiple threads. This can be enabled via optional keyword argument `check_same_thread`: ``` sqlite.connect(":memory:", check_same_thread=False) ```
What values to use for FastCGI maxrequests, maxspare, minspare, maxchildren?
393,629
5
2008-12-26T08:49:51Z
393,636
13
2008-12-26T09:00:13Z
[ "python", "django", "fastcgi" ]
I'm running a Django app using FastCGI and lighttpd. Can somebody explain me what I should consider when deciding what value to use for maxrequests, maxspare, minspare, maxchildren? These options are not too well documented, but seem quite important. Don't just tell me what they do; I want to understand what *implications* they have and how I should decide on what values to use. Thanks.
Let's start with the definition ``` maxrequests: How many requests does a child server before being killed and a new one forked maxspare : Maximum number of spare processes to keep running minspare : Minimum number of spare processes to prefork maxchildren: Hard limit number of processes in prefork mode ``` This means that you'll have at most *maxchildren* processes running at any given time in your webserver, each running for *maxrequests* requests. At server start you'll get *minspare* processes, which will keep growing until *maxspare* (or *maxchildren*) if more requests are coming. So, *minspare* lets you say how many concurrent requests are you expecting at a minimum (important to avoid the process creation if you start with one, it's good to start at, say 10), and *maxspare* lets you say how many concurrent requests will your server attend to at most (without compromising it's expected response time and so on. Needs a stress test to validate). And *maxrequests* is talking about the lifetime of each child, in case they cannot run forever due to any kind of constraint.
python and regular expression with unicode
393,843
57
2008-12-26T14:40:04Z
393,856
75
2008-12-26T14:57:57Z
[ "python", "regex", "character-properties" ]
I need to delete some unicode symbols from the string 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ' I know they exist here for sure. I try: ``` re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ') ``` but it doesn't work. String stays the same. ant suggestion what i do wrong?
Are you using python 2.x or 3.0? If you're using 2.x, try making the regex string a unicode-escape string, with 'u'. Since it's regex it's good practice to make your regex string a raw string, with 'r'. Also, putting your entire pattern in parentheses is superfluous. ``` re.sub(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+', '', ...) ``` <http://docs.python.org/tutorial/introduction.html#unicode-strings> Edit: It's also good practice to use the re.UNICODE/re.U/(?u) flag for unicode regexes, but it only affects character class aliases like \w or \b, of which this pattern does not use any and so would not be affected by.
python and regular expression with unicode
393,843
57
2008-12-26T14:40:04Z
393,915
44
2008-12-26T15:55:11Z
[ "python", "regex", "character-properties" ]
I need to delete some unicode symbols from the string 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ' I know they exist here for sure. I try: ``` re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ') ``` but it doesn't work. String stays the same. ant suggestion what i do wrong?
Use [unicode](http://www.amk.ca/python/howto/unicode) strings. Use the [re.UNICODE](http://docs.python.org/library/re.html#re.UNICODE) flag. ``` >>> myre = re.compile(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+', re.UNICODE) >>> myre <_sre.SRE_Pattern object at 0xb20b378> >>> mystr = u'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ' >>> result = myre.sub('', mystr) >>> len(mystr), len(result) (38, 22) >>> print result بسم الله الرحمن الرحيم ``` Read the article by *Joel Spolsky* called [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)
Scripting inside a Python application
393,871
4
2008-12-26T15:12:10Z
393,897
8
2008-12-26T15:36:49Z
[ "python", "scripting" ]
I'd like to include **Python scripting** in one of my applications, that is written in Python itself. My application must be able to call external Python functions (written by the user) as **callbacks**. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that. What is the best way to do this? Thanks. *edit*: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.
Use `__import__` to import the files provided by the user. This function will return a module. Use that to call the functions from the imported file. Use `try..except` both on `__import__` and on the actual call to catch errors. Example: ``` m = None try: m = __import__("external_module") except: # invalid module - show error if m: try: m.user_defined_func() except: # some error - display it ```
Scripting inside a Python application
393,871
4
2008-12-26T15:12:10Z
393,921
7
2008-12-26T16:01:20Z
[ "python", "scripting" ]
I'd like to include **Python scripting** in one of my applications, that is written in Python itself. My application must be able to call external Python functions (written by the user) as **callbacks**. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that. What is the best way to do this? Thanks. *edit*: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.
If you'd like the user to interactively enter commands, I can highly recommend the [code](http://docs.python.org/library/code.html) module, part of the standard library. The InteractiveConsole and InteractiveInterpreter objects allow for easy entry and evaluation of user input, and errors are handled very nicely, with tracebacks available to help the user get it right. Just make sure to catch SystemExit! ``` $ python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> shared_var = "Set in main console" >>> import code >>> ic = code.InteractiveConsole({ 'shared_var': shared_var }) >>> try: ... ic.interact("My custom console banner!") ... except SystemExit, e: ... print "Got SystemExit!" ... My custom console banner! >>> shared_var 'Set in main console' >>> shared_var = "Set in sub-console" >>> sys.exit() Got SystemExit! >>> shared_var 'Set in main console' ```
Python POST data using mod_wsgi
394,465
14
2008-12-26T23:35:59Z
394,543
21
2008-12-27T01:22:33Z
[ "python", "mod-wsgi" ]
This must be a very simple question, but I don't seem to be able to figure out. I'm using apache + mod\_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand? Edit: Tried already: * environ["CONTENT\_TYPE"] = 'application/x-www-form-urlencoded' (no data) * environ["wsgi.input"] seems a plausible way, however, both environ["wsgi.input"].read(), and environ["wsgi.input"].read(-1) returns an empty string (yes, content has been posted, and environ["request\_method"] = "post"
[PEP 333](http://www.python.org/dev/peps/pep-0333/) says [you must read environ['wsgi.input']](http://www.python.org/dev/peps/pep-0333/#input-and-error-streams). I just saved the following code and made apache's mod\_wsgi run it. It works. You must be doing something wrong. ``` from pprint import pformat def application(environ, start_response): # show the environment: output = ['<pre>'] output.append(pformat(environ)) output.append('</pre>') #create a simple form: output.append('<form method="post">') output.append('<input type="text" name="test">') output.append('<input type="submit">') output.append('</form>') if environ['REQUEST_METHOD'] == 'POST': # show form data as received by POST: output.append('<h1>FORM DATA</h1>') output.append(pformat(environ['wsgi.input'].read())) # send results output_len = sum(len(line) for line in output) start_response('200 OK', [('Content-type', 'text/html'), ('Content-Length', str(output_len))]) return output ```
Python POST data using mod_wsgi
394,465
14
2008-12-26T23:35:59Z
1,038,071
13
2009-06-24T12:31:53Z
[ "python", "mod-wsgi" ]
This must be a very simple question, but I don't seem to be able to figure out. I'm using apache + mod\_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand? Edit: Tried already: * environ["CONTENT\_TYPE"] = 'application/x-www-form-urlencoded' (no data) * environ["wsgi.input"] seems a plausible way, however, both environ["wsgi.input"].read(), and environ["wsgi.input"].read(-1) returns an empty string (yes, content has been posted, and environ["request\_method"] = "post"
Be aware that technically speaking calling read() or read(-1) on wsgi.input is a violation of the WSGI specification even though Apache/mod\_wsgi allows it. This is because the WSGI specification requires that a valid length argument be supplied. The WSGI specification also says you shouldn't read more data than is specified by the CONTENT\_LENGTH. So, the code above may work in Apache/mod\_wsgi but it isn't portable WSGI code and will fail on some other WSGI implementations. To be correct, determine request content length and supply that value to read().
Override a method at instance level
394,770
33
2008-12-27T07:12:07Z
394,779
80
2008-12-27T07:35:02Z
[ "python" ]
Is there a way in Python to override a class method at instance level? For example: ``` class Dog: def bark(self): print "WOOF" boby = Dog() boby.bark() # WOOF # METHOD OVERRIDE boby.bark() # WoOoOoF!! ```
Yes, it's possible: ``` class Dog: def bark(self): print "Woof" def new_bark(self): print "Woof Woof" foo = Dog() funcType = type(Dog.bark) # "Woof" foo.bark() # replace bark with new_bark for this object only foo.bark = funcType(new_bark, foo, Dog) foo.bark() # "Woof Woof" ```
Override a method at instance level
394,770
33
2008-12-27T07:12:07Z
394,788
20
2008-12-27T07:46:45Z
[ "python" ]
Is there a way in Python to override a class method at instance level? For example: ``` class Dog: def bark(self): print "WOOF" boby = Dog() boby.bark() # WOOF # METHOD OVERRIDE boby.bark() # WoOoOoF!! ```
``` class Dog: def bark(self): print "WOOF" boby = Dog() boby.bark() # WOOF # METHOD OVERRIDE def new_bark(): print "WoOoOoF!!" boby.bark = new_bark boby.bark() # WoOoOoF!! ``` You can use the `boby` variable inside the function if you need. Since you are overriding the method just for this one instance object, this way is simpler and has exactly the same effect as using `self`.
Override a method at instance level
394,770
33
2008-12-27T07:12:07Z
395,006
23
2008-12-27T13:44:45Z
[ "python" ]
Is there a way in Python to override a class method at instance level? For example: ``` class Dog: def bark(self): print "WOOF" boby = Dog() boby.bark() # WOOF # METHOD OVERRIDE boby.bark() # WoOoOoF!! ```
Please do not do this as shown. You code becomes unreadable when you monkeypatch an instance to be different from the class. You cannot debug monkeypatched code. When you find a bug in `boby` and `print type(boby)`, you'll see that (a) it's a Dog, but (b) for some obscure reason it doesn't bark correctly. This is a nightmare. Do not do it. Please do this instead. ``` class Dog: def bark(self): print "WOOF" class BobyDog( Dog ): def bark( self ): print "WoOoOoF!!" otherDog= Dog() otherDog.bark() # WOOF boby = BobyDog() boby.bark() # WoOoOoF!! ```
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
394,814
3,110
2008-12-27T08:44:19Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
Yes, it was [added](https://mail.python.org/pipermail/python-dev/2005-September/056846.html) in version 2.5. The syntax is: ``` a if condition else b ``` First `condition` is evaluated, then either `a` or `b` is returned based on the [Boolean](https://en.wikipedia.org/wiki/Boolean_data_type) value of `condition` If `condition` evaluates to *True* `a` is returned, else `b` is returned. For example: ``` >>> 'true' if True else 'false' 'true' >>> 'true' if False else 'false' 'false' ``` Keep in mind that it's frowned upon by some Pythonistas for several reasons: * The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order). * Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects). * Stylistic reasons. If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean. For example, `x = 4 if b > 8 else 9` is read aloud as `x will be 4 if b is greater than 8 otherwise 9`. Official documentation: * [Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions) * [Is there an equivalent of C’s ”?:” ternary operator?](https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator)
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
394,815
70
2008-12-27T08:44:23Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
From [the documentation](https://docs.python.org/3/reference/expressions.html#conditional-expressions): > Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations. > > The expression `x if C else y` first evaluates the condition, *C* (*not x*); if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated and its value is returned. > > See [PEP 308](https://www.python.org/dev/peps/pep-0308/) for more details about conditional expressions. New since version 2.5.
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
394,887
152
2008-12-27T10:48:27Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
For versions prior to 2.5, there's the trick: ``` [expression] and [on_true] or [on_false] ``` It can give wrong results when `on_true` has a false boolean value.1 Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion. 1. [Is there an equivalent of C’s ”?:” ternary operator?](http://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator)
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
470,376
359
2009-01-22T18:58:09Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
You can index into a tuple: ``` (falseValue, trueValue)[test] ``` `test` needs to return *True* or *False*. It might be safer to always implement it as: ``` (falseValue, trueValue)[test == True] ``` or you can use the built-in [`bool()`](https://docs.python.org/3.3/library/functions.html#bool) to assure a [Boolean](https://en.wikipedia.org/wiki/Boolean_data_type) value: ``` (falseValue, trueValue)[bool(<expression>)] ```
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
1,855,173
40
2009-12-06T11:51:50Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
@up: Unfortunately, the ``` (falseValue, trueValue)[test] ``` solution doesn't have short-circuit behaviour; thus both falseValue and trueValue are evaluated regardless of the condition. This could be suboptimal or even buggy (i.e. both trueValue and falseValue could be methods and have side-effects). One solution to this would be ``` (falseValue, trueValue)[test]() ``` (execution delayed until the winner is known ;)), but it introduces inconsistency between callable and non-callable objects. In addition, it doesn't solve the case when using properties. And so the story goes - choosing between 3 mentioned solutions is a trade-off between having the short-circuit feature, using at least python 2.5 (IMHO not a problem anymore) and not being prone to "trueValue-evaluates-to-false" errors.
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
2,919,360
79
2010-05-27T07:56:06Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
*expression1* if *condition* else *expression2* ``` >>> a = 1 >>> b = 2 >>> 1 if a > b else -1 -1 >>> 1 if a > b else -1 if a < b else 0 -1 ```
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
10,314,837
30
2012-04-25T11:40:11Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
For Python 2.5 and newer there is a specific syntax: ``` [on_true] if [cond] else [on_false] ``` In older Pythons a ternary operator is not implemented but it's possible to simulate it. ``` cond and on_true or on_false ``` Though, there is a potential problem, which if `cond` evaluates to `True` and `on_true` evaluates to `False` then `on_false` is returned instead of `on_true`. If you want this behavior the method is OK, otherwise use this: ``` {True: on_true, False: on_false}[cond is True] # is True, not == True ``` which can be wrapped by: ``` def q(cond, on_true, on_false) return {True: on_true, False: on_false}[cond is True] ``` and used this way: ``` q(cond, on_true, on_false) ``` It is compatible with all Python versions.
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
14,321,907
19
2013-01-14T15:56:09Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
You might often find ``` cond and on_true or on_false ``` but this lead to problem when on\_true == 0 ``` >>> x = 0 >>> print x == 0 and 0 or 1 1 >>> x = 1 >>> print x == 0 and 0 or 1 1 ``` where you would expect for a normal ternary operator this result ``` >>> x = 0 >>> print 0 if x == 0 else 1 0 >>> x = 1 >>> print 0 if x == 0 else 1 1 ```
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
20,093,702
10
2013-11-20T10:44:12Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
Simulating the python ternary operator. For example ``` a, b, x, y = 1, 2, 'a greather than b', 'b greater than a' result = (lambda:y, lambda:x)[a > b]() ``` output: ``` 'b greater than a' ```
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
30,052,371
33
2015-05-05T12:00:09Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
An operator for a conditional expression in Python was added in 2006 as part of [Python Enhancement Proposal 308](https://www.python.org/dev/peps/pep-0308/). Its form differ from common `?:` operator and it's: ``` <expression1> if <condition> else <expression2> ``` which is equivalent to: ``` if <condition>: <expression1> else: <expression2> ``` Here is example: ``` result = x if a > b else y ``` Another syntax which can be used (compatible with versions before 2.5): ``` result = (lambda:y, lambda:x)[a > b]() ``` where operands are [lazily evaluated](https://en.wikipedia.org/wiki/Lazy_evaluation). Another way is by indexing a tuple (which isn't consistent with the conditional operator of most other languages): ``` result = (y, x)[a > b] ``` or explicitly constructed dictionary: ``` result = {True: x, False: y}[a > b] ``` Another (less reliable), but simpler method is to use `and` and `or` operators: ``` result = (a > b) and x or y ``` however this won't work if `x` would be `False`. As possible workaround is to make `x` and `y` lists or tuples as in the following: ``` result = ((a > b) and [x] or [y])[0] ``` or: ``` result = ((a > b) and (x,) or (y,))[0] ``` If you're working with dictionaries, instead of using a ternary conditional, you can take advantage of [`get(key, default)`](https://docs.python.org/3/library/stdtypes.html#dict.get), for example: ``` shell = os.environ.get('SHELL', "/bin/sh") ``` Source: [?: in Python at Wikipedia](https://en.wikipedia.org/wiki/%3F:#Python)
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
31,429,254
11
2015-07-15T11:33:41Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
Absolutely, and it is incredibly easy to understand. ``` general syntax : first_expression if bool_expression== true else second_expression Example: x= 3 if 3 > 2 else 4 # assigns 3 to x if the boolean expression evaluates to true or 4 if it is false ```
Does Python have a ternary conditional operator?
394,809
2,655
2008-12-27T08:32:18Z
33,765,206
12
2015-11-17T19:14:33Z
[ "python", "operators", "ternary-operator", "conditional-operator", "python-2.5" ]
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
> # Does Python have a ternary conditional operator? Yes. From the [grammar file](https://docs.python.org/reference/grammar.html): ``` test: or_test ['if' or_test 'else' test] | lambdef ``` The part of interest is: ``` or_test ['if' or_test 'else' test] ``` So, a ternary conditional operation is of the form: ``` expression1 if expression2 else expression3 ``` `expression3` will be lazily evaluated (that is, evaluated only if `expression2` is false in a boolean context). And because of the recursive definition, you can chain them indefinitely (though it may considered bad style.) ``` expression1 if expression2 else expression3 if expression4 else expression5 # and so on ``` ### A note on usage: Note that every `if` must be followed with an `else`. People learning list comprehensions and generator expressions may find this to be a difficult lesson to learn - the following will not work, as Python expects a third expression for an else: ``` [expression1 if expression2 for element in iterable] # ^-- need an else here ``` which raises a `SyntaxError: invalid syntax`. So the above is either an incomplete piece of logic (perhaps the user expects a no-op in the false condition) or what may be intended is to use expression2 as a filter - notes that the following is legal Python: ``` [expression1 for element in iterable if expression2] ``` `expression2` works as a filter for the list comprehension, and is *not* a ternary conditional operator. ### Alternative syntax for a more narrow case: You may find it somewhat painful to write the following: ``` expression1 if expression1 else expression2 ``` `expression1` will have to be evaluated twice with the above usage. It can limit redundancy if it is simply a local variable. However, a common and performant Pythonic idiom for this use-case is to use `or`'s shortcutting behavior: ``` expression1 or expression2 ``` which is equivalent in semantics. Note that some style-guides may limit this usage on the grounds of clarity - it does pack a lot of meaning into very little syntax.
Python threads stack_size and segfaults
394,895
2
2008-12-27T11:03:00Z
394,916
9
2008-12-27T11:28:29Z
[ "python", "multithreading", "segmentation-fault", "stack-size" ]
A web crawler script that spawns at most 500 threads and each thread basically requests for certain data served from the remote server, which each server's reply is different in content and size from others. i'm setting stack\_size as 756K's for threads ``` threading.stack_size(756*1024) ``` which enables me to have the sufficient number of threads required and complete most of the jobs and requests. But as some servers' responses are bigger than others, and when a thread gets that kind of response, script dies with SIGSEGV. stack\_sizes more than 756K makes it impossible to have the required number of threads at the same time. any suggestions on how can i continue with given stack\_size without crashes? and how can i get the current used stack\_size of any given thread?
**Why** on earth are you spawning 500 threads? That seems like a terrible idea! Remove threading completely, use an event loop to do the crawling. Your program will be faster, simpler, and easier to maintain. Lots of threads waiting for network won't make your program *wait faster*. Instead, collect all open sockets in a list and run a loop where you check if any of them has data available. I recommend using [Twisted](http://twistedmatrix.com) - It is an event-driven networking engine. It is very flexile, secure, scalable and very stable (no segfaults). You could also take a look at [Scrapy](http://scrapy.org/) - It is a web crawling and screen scraping framework written in Python/Twisted. It is still under heavy development, but maybe you can take some ideas.
Can I use a ForeignKey in __unicode__ return?
395,340
11
2008-12-27T19:58:22Z
395,347
24
2008-12-27T20:02:38Z
[ "python", "django", "django-models" ]
I have the following classes: Ingredients, Recipe and RecipeContent... ``` class Ingredient(models.Model): name = models.CharField(max_length=30, primary_key=True) qty_on_stock = models.IntegerField() def __unicode__(self): return self.name class Recipe(models.Model): name = models.CharField(max_length=30, primary_key=True) comments = models.TextField(blank=True) ingredient = models.ManyToManyField(Ingredient) def __unicode__(self): return self.name class RecipeContent(models.Model): recipe = models.ForeignKey(Recipe) ingredients = models.ForeignKey(Ingredient) qty_used = models.IntegerField() ``` but for \_\_unicode\_\_() in RecipeContent I would like to use the Recipe name to which this RecipeContent belongs to... is there a way to do it?
``` class RecipeContent(models.Model): ... def __unicode__(self): # You can access ForeignKey properties through the field name! return self.recipe.name ```
How to download a file over http with authorization in python 3.0, working around bugs?
395,451
6
2008-12-27T21:45:47Z
395,481
19
2008-12-27T22:04:53Z
[ "python", "python-3.x", "urllib" ]
I have a script that I'd like to continue using, but it looks like I either have to find some workaround for a bug in Python 3, or downgrade back to 2.6, and thus having to downgrade other scripts as well... Hopefully someone here have already managed to find a workaround. The problem is that due to the new changes in Python 3.0 regarding bytes and strings, not all the library code is apparently tested. I have a script that downloades a page from a web server. This script passed a username and password as part of the url in python 2.6, but in Python 3.0, this doesn't work any more. For instance, this: ``` import urllib.request; url = "http://username:password@server/file"; urllib.request.urlretrieve(url, "temp.dat"); ``` fails with this exception: ``` Traceback (most recent call last): File "C:\Temp\test.py", line 5, in <module> urllib.request.urlretrieve(url, "test.html"); File "C:\Python30\lib\urllib\request.py", line 134, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, data) File "C:\Python30\lib\urllib\request.py", line 1476, in retrieve fp = self.open(url, data) File "C:\Python30\lib\urllib\request.py", line 1444, in open return getattr(self, name)(url) File "C:\Python30\lib\urllib\request.py", line 1618, in open_http return self._open_generic_http(http.client.HTTPConnection, url, data) File "C:\Python30\lib\urllib\request.py", line 1576, in _open_generic_http auth = base64.b64encode(user_passwd).strip() File "C:\Python30\lib\base64.py", line 56, in b64encode raise TypeError("expected bytes, not %s" % s.__class__.__name__) TypeError: expected bytes, not str ``` Apparently, base64-encoding now needs bytes in and outputs a string, and thus urlretrieve (or some code therein) which builds up a string of username:password, and tries to base64-encode this for simple authorization, fails. If I instead try to use urlopen, like this: ``` import urllib.request; url = "http://username:password@server/file"; f = urllib.request.urlopen(url); contents = f.read(); ``` Then it fails with this exception: ``` Traceback (most recent call last): File "C:\Temp\test.py", line 5, in <module> f = urllib.request.urlopen(url); File "C:\Python30\lib\urllib\request.py", line 122, in urlopen return _opener.open(url, data, timeout) File "C:\Python30\lib\urllib\request.py", line 359, in open response = self._open(req, data) File "C:\Python30\lib\urllib\request.py", line 377, in _open '_open', req) File "C:\Python30\lib\urllib\request.py", line 337, in _call_chain result = func(*args) File "C:\Python30\lib\urllib\request.py", line 1082, in http_open return self.do_open(http.client.HTTPConnection, req) File "C:\Python30\lib\urllib\request.py", line 1051, in do_open h = http_class(host, timeout=req.timeout) # will parse host:port File "C:\Python30\lib\http\client.py", line 620, in __init__ self._set_hostport(host, port) File "C:\Python30\lib\http\client.py", line 632, in _set_hostport raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) http.client.InvalidURL: nonnumeric port: 'password@server' ``` Apparently the url parsing in this "next gen url retrieval library" doesn't know what to do with username and passwords in the url. What other choices do I have?
Direct from the Py3k docs: <http://docs.python.org/dev/py3k/library/urllib.request.html#examples> ``` import urllib.request # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib.request.HTTPBasicAuthHandler() auth_handler.add_password(realm='PDQ Application', uri='https://mahler:8092/site-updates.py', user='klem', passwd='kadidd!ehopper') opener = urllib.request.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib.request.install_opener(opener) urllib.request.urlopen('http://www.example.com/login.html') ```
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X?
395,509
6
2008-12-27T22:23:48Z
395,568
12
2008-12-27T23:09:42Z
[ "python", "mysql", "django", "osx", "sysadmin" ]
I'm new to the Mac OS X, and I'm just about ready to throw my brand new [MacBook Pro](http://en.wikipedia.org/wiki/MacBook_Pro) out the window. Every tutorial on setting up a Django development environment on [Mac OS X Leopard](http://en.wikipedia.org/wiki/Mac_OS_X_Leopard) is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know one thing that I must not. I'm very familiar with how to setup the environment on Ubuntu/Linux, and the only part I'm getting stuck on with [OS X](https://en.wikipedia.org/wiki/OS_X) is how to install MySQL, autostart it, and install the Python MySQL bindings. I think my mistake was using a hodgepodge of tools I don't fully understand; I used fink to install MySQL and its development libraries and then tried to build the Python-MySQL bindings from source (but they won't build.) UPDATE: I installed the binary MySQL package from <http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg>, and I got MySQL server running (can access with admin.) The MySQL version I got from port was rubbish, I could not get it to run at all. I modified the source for the Python-MySQL package as per the answer I chose, but I still got compilation errors that I listed in the comments. I was able to fix these by adding /usr/local/mysql/bin/ to my path in my "~/.profile" file. " PATH=/usr/local/mysql/bin:$PATH " Thanks for the help, I was very wary about editing the source code since this operation had been so easy on Ubuntu, but I'll be more willing to try that in the future. I'm really missing Ubuntu's "apt-get" command; it makes life very easy and simple sometimes. I already have an Ubuntu [VMware](http://en.wikipedia.org/wiki/VMware) image running on my Mac, so I can always use that as a fallback (plus it more closely matches my production machines so should be a good test environment for debugging production problems.)
Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does `/usr/local/mysql/include` contain lots of header files? (I've got 46 header files there, for reference). If so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, however. [This](http://www.keningle.com/?p=11) is a decent guide: I've included the salient steps below. --- 1. Download the [MySQL-python source](https://sourceforge.net/projects/mysql-python) (v1.2.2 at time of writing: all subsequent instructions are for this version) ``` $ tar xzf MySQL-python-1.2.2.tar.gz && cd MySQL-python-1.2.2 ``` 2. Edit `_mysql.c`: remove lines 37-39 and change lines 481-482. Here's the diff: ``` 37,39d36 < #ifndef uint < #define uint unsigned int < #endif 484,485c481,482 < uint port = MYSQL_PORT; < uint client_flag = 0; --- > unsigned int port = MYSQL_PORT; > unsigned int client_flag = 0; ``` 3. Symlink the libs to where MySQL-python expects them: ``` $ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql ``` 4. In your MySQL-python-1.2.2 directory, rebuild your package: ``` $ sudo python setup.py build ``` **Note:** You will receive a warning, ignore it. 5. Install the package: ``` $ sudo python setup.py install ``` --- As for starting MySQL, there are instructions [here](http://dev.mysql.com/doc/refman/5.0/en/mac-os-x-installation.html) on starting it as a service. Personally, I just run ``` sudo mysqld_safe ``` manually, backgrounding it with `^Z` and `bg` once I've put in my password.
Threads in Python
395,704
6
2008-12-28T02:22:38Z
395,716
13
2008-12-28T02:40:43Z
[ "python", "multithreading" ]
General tutorial or good resource on how to use threads in Python? When to use threads, how they are effective, and some general background on threads [specific to Python]?
Threads should be used when you want two things to run at once, or want something to run in the background without slowing down the main process. My recommendation is to only use threads if you have to. They generally add complexity to a program. The main documentation for threading is here: <http://docs.python.org/library/threading.html> Some examples are here: <http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/> <http://linuxgazette.net/107/pai.html> <http://www.wellho.net/solutions/python-python-threads-a-first-example.html>
Threads in Python
395,704
6
2008-12-28T02:22:38Z
396,055
8
2008-12-28T10:22:05Z
[ "python", "multithreading" ]
General tutorial or good resource on how to use threads in Python? When to use threads, how they are effective, and some general background on threads [specific to Python]?
One thing to remember before spending time and effort in writing a multi-threaded Python application is that there is a [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock) (GIL), so you won't actually be running more than one thread at a time. This makes threading unsuitable for trying to take advantage of multiple cores or CPUs. You may get some speedup from multiplexing other resources (network, disk, ...), but it's never been particularly noticeable in my experience. In general, I only use threads when there are several logically separate tasks happening at once, and yet I want them all in the same VM. A thread pulling data from the web and putting it on a Queue, while another thread pops from the Queue and writes to a database, something like that. With Python 2.6, there is the new `multiprocessing` module which is pretty cool - it's got a very similar interface to the `threading` module, but actually spawns new OS processes, sidestepping the GIL.
How to check whether a variable is a class or not?
395,735
119
2008-12-28T03:08:05Z
395,741
17
2008-12-28T03:11:54Z
[ "python", "reflection" ]
I was wondering how to check whether a variable is a class (not an instance!) or not. I've tried to use the function `isinstance(object, class_or_type_or_tuple)` to do this, but I don't know what type would a class will have. For example, in the following code ``` class Foo: pass isinstance(Foo, **???**) # i want to make this return True. ``` I tried to substitute "`class`" with **???**, but I realized that `class` is a keyword in python.
``` >>> class X(object): ... pass ... >>> type(X) <type 'type'> >>> isinstance(X,type) True ```
How to check whether a variable is a class or not?
395,735
119
2008-12-28T03:08:05Z
395,782
178
2008-12-28T03:47:00Z
[ "python", "reflection" ]
I was wondering how to check whether a variable is a class (not an instance!) or not. I've tried to use the function `isinstance(object, class_or_type_or_tuple)` to do this, but I don't know what type would a class will have. For example, in the following code ``` class Foo: pass isinstance(Foo, **???**) # i want to make this return True. ``` I tried to substitute "`class`" with **???**, but I realized that `class` is a keyword in python.
Even better: use the [`inspect.isclass`](https://docs.python.org/library/inspect.html#inspect.isclass) function. ``` >>> import inspect >>> class X(object): ... pass ... >>> inspect.isclass(X) True >>> x = X() >>> isinstance(x, X) True >>> y = 25 >>> isinstance(y, X) False ```
How to check whether a variable is a class or not?
395,735
119
2008-12-28T03:08:05Z
10,123,520
29
2012-04-12T12:24:08Z
[ "python", "reflection" ]
I was wondering how to check whether a variable is a class (not an instance!) or not. I've tried to use the function `isinstance(object, class_or_type_or_tuple)` to do this, but I don't know what type would a class will have. For example, in the following code ``` class Foo: pass isinstance(Foo, **???**) # i want to make this return True. ``` I tried to substitute "`class`" with **???**, but I realized that `class` is a keyword in python.
The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented ``` def isclass(object): """Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined""" return isinstance(object, (type, types.ClassType)) ```
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly?
395,982
23
2008-12-28T08:41:45Z
396,109
14
2008-12-28T11:36:08Z
[ "python", "types", "metaclass", "super" ]
I have read posts like these: 1. [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) 2. [What are your (concrete) use-cases for metaclasses in Python?](http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python) 3. [Python's Super is nifty, but you can't use it](http://fuhm.net/super-harmful/) But somehow I got confused. Many confusions like: When and why would I have to do something like the following? ``` # Refer link1 return super(MyType, cls).__new__(cls, name, bases, newattrs) ``` or ``` # Refer link2 return super(MetaSingleton, cls).__call__(*args, **kw) ``` or ``` # Refer link2 return type(self.__name__ + other.__name__, (self, other), {}) ``` How does super work exactly? What is class registry and unregistry in link1 and how exactly does it work? (I thought it has something to do with [singleton](http://en.wikipedia.org/wiki/Singleton_pattern). I may be wrong, being from C background. My coding style is still a mix of functional and OO). What is the flow of class instantiation (subclass, metaclass, super, type) and method invocation ( ``` metaclass->__new__, metaclass->__init__, super->__new__, subclass->__init__ inherited from metaclass ``` ) with well-commented working code (though the first link is quite close, but it does not talk about cls keyword and super(..) and registry). Preferably an example with multiple inheritance. P.S.: I made the last part as code because Stack Overflow formatting was converting the text `metaclass->__new__` to metaclass->**new**
OK, you've thrown quite a few concepts into the mix here! I'm going to pull out a few of the specific questions you have. In general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python. [Python's own documentation](http://docs.python.org/reference/datamodel.html) is a very good reference, and completely up to date. There is an [IBM developerWorks article](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) which is fine as an introduction and takes a more tutorial-based approach, but note that it's five years old, and spends a lot of time talking about the older-style approaches to meta-classes. **`super`** is how you access an object's super-classes. It's more complex than (for example) Java's `super` keyword, mainly because of multiple inheritance in Python. As [Super Considered Harmful](http://fuhm.net/super-harmful/) explains, using `super()` can result in you implicitly using a chain of super-classes, the order of which is defined by the [Method Resolution Order](http://www.python.org/download/releases/2.3/mro/) (MRO). You can see the MRO for a class easily by invoking `mro()` on the class (not on an instance). Note that meta-classes are not in an object's super-class hierarchy. [Thomas](http://stackoverflow.com/users/17624/thomas-wouters)' description of meta-classes [here](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) is excellent: > A metaclass is the class of a class. > Like a class defines how an instance > of the class behaves, a metaclass > defines how a class behaves. A class > is an instance of a metaclass. In the examples you give, here's what's going on: 1. The call to `__new__` is being bubbled up to the next thing in the MRO. In this case, `super(MyType, cls)` would resolve to `type`; calling `type.__new__` lets Python complete it's normal instance creation steps. 2. This example is using meta-classes to enforce a singleton. He's overriding `__call__` in the metaclass so that whenever a class instance is created, he intercepts that, and can bypass instance creation if there already is one (stored in `cls.instance`). Note that overriding `__new__` in the metaclass won't be good enough, because that's only called when creating the *class*. Overriding `__new__` on the class would work, however. 3. This shows a way to dynamically create a class. Here's he's appending the supplied class's name to the created class name, and adding it to the class hierarchy too. I'm not exactly sure what sort of code example you're looking for, but here's a brief one showing meta-classes, inheritance and method resolution: ``` class MyMeta(type): def __new__(cls, name, bases, dct): print "meta: creating %s %s" % (name, bases) return type.__new__(cls, name, bases, dct) def meta_meth(cls): print "MyMeta.meta_meth" __repr__ = lambda c: c.__name__ class A(object): __metaclass__ = MyMeta def __init__(self): super(A, self).__init__() print "A init" def meth(self): print "A.meth" class B(object): __metaclass__ = MyMeta def __init__(self): super(B, self).__init__() print "B init" def meth(self): print "B.meth" class C(A, B): __metaclass__ = MyMeta def __init__(self): super(C, self).__init__() print "C init" >>> c_obj = C() meta: creating A (<type 'object'>,) meta: creating B (<type 'object'>,) meta: creating C (A, B) B init A init C init >>> c_obj.meth() A.meth >>> C.meta_meth() MyMeta.meta_meth >>> c_obj.meta_meth() Traceback (most recent call last): File "mro.py", line 38, in <module> c_obj.meta_meth() AttributeError: 'C' object has no attribute 'meta_meth' ```
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly?
395,982
23
2008-12-28T08:41:45Z
396,192
9
2008-12-28T14:11:03Z
[ "python", "types", "metaclass", "super" ]
I have read posts like these: 1. [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) 2. [What are your (concrete) use-cases for metaclasses in Python?](http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python) 3. [Python's Super is nifty, but you can't use it](http://fuhm.net/super-harmful/) But somehow I got confused. Many confusions like: When and why would I have to do something like the following? ``` # Refer link1 return super(MyType, cls).__new__(cls, name, bases, newattrs) ``` or ``` # Refer link2 return super(MetaSingleton, cls).__call__(*args, **kw) ``` or ``` # Refer link2 return type(self.__name__ + other.__name__, (self, other), {}) ``` How does super work exactly? What is class registry and unregistry in link1 and how exactly does it work? (I thought it has something to do with [singleton](http://en.wikipedia.org/wiki/Singleton_pattern). I may be wrong, being from C background. My coding style is still a mix of functional and OO). What is the flow of class instantiation (subclass, metaclass, super, type) and method invocation ( ``` metaclass->__new__, metaclass->__init__, super->__new__, subclass->__init__ inherited from metaclass ``` ) with well-commented working code (though the first link is quite close, but it does not talk about cls keyword and super(..) and registry). Preferably an example with multiple inheritance. P.S.: I made the last part as code because Stack Overflow formatting was converting the text `metaclass->__new__` to metaclass->**new**
Here's the more pragmatic answer. **It rarely matters** 1. "[What is a metaclass in Python](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python)". Bottom line, `type` is the metaclass of all classes. You have almost no practical use for this. ``` class X(object): pass type(X) == type ``` 2. "[What are your (concrete) use cases for metaclasses in Python?](http://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python)". Bottom line. None. 3. "[Python's Super is nifty, but you can't use it](http://fuhm.net/super-harmful/)". Interesting note, but little practical value. You'll never have a need for resolving complex multiple inheritance networks. It's easy to prevent this problem from arising by using an explicity **Strategy** design instead of multiple inheritance. Here's my experience over the last 7 years of Python programming. 1. A class has 1 or more superclasses forming a simple chain from my class to `object`. 2. The concept of "class" is defined by a metaclass named `type`. I might want to extend the concept of "class", but so far, it's never come up in practice. Not once. `type` always does the right thing. 3. Using `super` works out really well in practice. It allows a subclass to defer to it's superclass. It happens to show up in these metaclass examples because they're extending the built-in metaclass, `type`. However, in all subclass situations, you'll make use of `super` to extend a superclass. **Metaclasses** The metaclass issue is this: * Every object has a reference to it's type definition, or "class". * A `class` is, itself, also an object. * Therefore a object of type `class` has a reference to it's type or "class". The "class" of a "class" is a metaclass. Since a "class" isn't a C++ run-time object, this doesn't happen in C++. It does happen in Java, Smalltalk and Python. A metaclass defines the behavior of a class object. * 90% of your interaction with a class is to ask the class to create a new object. * 10% of the time, you'll be using class methods or class variables ("static" in C++ or Java parlance.) I have found a few use cases for class-level methods. I have almost no use cases for class variables. I've never had a situation to change the way object construction works.
Checking if two strings are permutations of each other in Python
396,421
15
2008-12-28T17:25:17Z
396,430
7
2008-12-28T17:33:11Z
[ "algorithm", "python" ]
I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways: ``` sorted(a) == sorted(b) ``` and ``` all(a.count(char) == b.count(char) for char in a) ``` but the first one is slower when (for example) the first char of `a` is nowhere in `b`, and the second is slower when they are actually permutations. Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?
I think the first one is the "obvious" way. It is shorter, clearer, and likely to be faster in many cases because Python's built-in sort is highly optimized.
Checking if two strings are permutations of each other in Python
396,421
15
2008-12-28T17:25:17Z
396,438
14
2008-12-28T17:40:03Z
[ "algorithm", "python" ]
I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways: ``` sorted(a) == sorted(b) ``` and ``` all(a.count(char) == b.count(char) for char in a) ``` but the first one is slower when (for example) the first char of `a` is nowhere in `b`, and the second is slower when they are actually permutations. Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?
Here is a way which is O(n), asymptotically better than the two ways you suggest. ``` import collections def same_permutation(a, b): d = collections.defaultdict(int) for x in a: d[x] += 1 for x in b: d[x] -= 1 return not any(d.itervalues()) ## same_permutation([1,2,3],[2,3,1]) #. True ## same_permutation([1,2,3],[2,3,1,1]) #. False ```
Checking if two strings are permutations of each other in Python
396,421
15
2008-12-28T17:25:17Z
396,523
14
2008-12-28T18:55:35Z
[ "algorithm", "python" ]
I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways: ``` sorted(a) == sorted(b) ``` and ``` all(a.count(char) == b.count(char) for char in a) ``` but the first one is slower when (for example) the first char of `a` is nowhere in `b`, and the second is slower when they are actually permutations. Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?
"but the first one is slower when (for example) the first char of a is nowhere in b". This kind of degenerate-case performance analysis is not a good idea. It's a rat-hole of lost time thinking up all kinds of obscure special cases. Only do the **O**-style "overall" analysis. Overall, the sorts are **O**( *n* log( *n* ) ). The `a.count(char) for char in a` solution is **O**( *n* 2 ). Each count pass is a full examination of the string. If some obscure special case happens to be faster -- or slower, that's possibly interesting. But it only matters when you know the frequency of your obscure special cases. When analyzing sort algorithms, it's important to note that a fair number of sorts involve data that's already in the proper order (either by luck or by a clever design), so sort performance on pre-sorted data matters. In your obscure special case ("the first char of a is nowhere in b") is this frequent enough to matter? If it's just a special case you thought of, set it aside. If it's a fact about your data, then consider it.
Checking if two strings are permutations of each other in Python
396,421
15
2008-12-28T17:25:17Z
396,570
7
2008-12-28T19:36:38Z
[ "algorithm", "python" ]
I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways: ``` sorted(a) == sorted(b) ``` and ``` all(a.count(char) == b.count(char) for char in a) ``` but the first one is slower when (for example) the first char of `a` is nowhere in `b`, and the second is slower when they are actually permutations. Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?
heuristically you're probably better to split them off based on string size. Pseudocode: ``` returnvalue = false if len(a) == len(b) if len(a) < threshold returnvalue = (sorted(a) == sorted(b)) else returnvalue = naminsmethod(a, b) return returnvalue ``` If performance is critical, and string size can be large or small then this is what I'd do. It's pretty common to split things like this based on input size or type. Algorithms have different strengths or weaknesses and it would be foolish to use one where another would be better... In this case Namin's method is O(n), but has a larger constant factor than the O(n log n) sorted method.
Python-PostgreSQL psycopg2 interface --> executemany
396,455
6
2008-12-28T17:51:48Z
550,849
8
2009-02-15T13:13:40Z
[ "python", "postgresql", "database", "psycopg" ]
I am currently analyzing a wikipedia dump file; I am extracting a bunch of data from it using python and persisting it into a PostgreSQL db. I am always trying to make things go faster for this file is huge (18GB). In order to interface with PostgreSQL, I am using psycopg2, but this module seems to mimic many other such DBAPIs. Anyway, I have a question concerning cursor.executemany(command, values); it seems to me like executing an executemany once every 1000 values or so is better than calling cursor.execute(command % value) for each of these 5 million values (please confirm or correct me!). But, you see, I am using an executemany to INSERT 1000 rows into a table which has a UNIQUE integrity constraint; this constraint is not verified in python beforehand, for this would either require me to SELECT all the time (this seems counter productive) or require me to get more than 3 GB of RAM. All this to say that I count on Postgres to warn me when my script tried to INSERT an already existing row via catching the psycopg2.DatabaseError. When my script detects such a non-UNIQUE INSERT, it connection.rollback() (which makes ups to 1000 rows everytime, and kind of makes the executemany worthless) and then INSERTs all values one by one. Since psycopg2 is so poorly documented (as are so many great modules...), I cannot find an efficient and effective workaround. I have reduced the number of values INSERTed per executemany from 1000 to 100 in order to reduce the likeliness of a non-UNIQUE INSERT per executemany, but I am pretty certain their is a way to just tell psycopg2 to ignore these execeptions or to tell the cursor to continue the executemany. Basically, this seems like the kind of problem which has a solution so easy and popular, that all I can do is ask in order to learn about it. Thanks again!
just copy all the data into a scratch table with the psql \copy command, or use the psycopg cursor.copy\_in() method. Then: ``` insert into mytable select * from ( select distinct * from scratch ) uniq where not exists ( select 1 from mytable where mytable.mykey = uniq.mykey ); ``` This will dedup and runs much faster than any combination of inserts. -dg
How to instantiate a class in python
396,856
41
2008-12-28T23:36:46Z
396,871
46
2008-12-28T23:48:05Z
[ "python", "python-3.x" ]
So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class. ``` class mystuff: def average(a,b,c): #get the average of three numbers result=a+b+c result=result/3 return result #now use the function average from the mystuff class print mystuff.average(9,18,27) File "class.py", line 7, in <module> print mystuff.average(9,18,27) TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead) ``` What's wrong?
You can instantiate the class by declaring a variable and calling the class as if it were a function: ``` x = mystuff() print x.average(9,18,27) ``` However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message: ``` TypeError: average() takes exactly 3 arguments (4 given) ``` To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.
How to instantiate a class in python
396,856
41
2008-12-28T23:36:46Z
396,876
30
2008-12-28T23:51:21Z
[ "python", "python-3.x" ]
So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class. ``` class mystuff: def average(a,b,c): #get the average of three numbers result=a+b+c result=result/3 return result #now use the function average from the mystuff class print mystuff.average(9,18,27) File "class.py", line 7, in <module> print mystuff.average(9,18,27) TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead) ``` What's wrong?
From your example, it seems to me you want to use a static method. ``` class mystuff: @staticmethod def average(a,b,c): #get the average of three numbers result=a+b+c result=result/3 return result print mystuff.average(9,18,27) ``` Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.
How to instantiate a class in python
396,856
41
2008-12-28T23:36:46Z
23,840,853
7
2014-05-24T02:51:04Z
[ "python", "python-3.x" ]
So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class. ``` class mystuff: def average(a,b,c): #get the average of three numbers result=a+b+c result=result/3 return result #now use the function average from the mystuff class print mystuff.average(9,18,27) File "class.py", line 7, in <module> print mystuff.average(9,18,27) TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead) ``` What's wrong?
To minimally modify your example, you could amend the code to: ``` class myclass(object): def __init__(self): # this method creates the class object. pass def average(self,a,b,c): #get the average of three numbers result=a+b+c result=result/3 return result mystuff=myclass() # by default the __init__ method is then called. print mystuff.average(a,b,c) ``` Or to expand it more fully, allowing you to add other methods. ``` #!/usr/bin/env python import sys class myclass(object): def __init__(self,a,b,c): self.a=a self.b=b self.c=c def average(self): #get the average of three numbers result=self.a+self.b+self.c result=result/3 return result a=9 b=18 c=27 mystuff=myclass(a, b, c) print mystuff.average() ```
In Python, how do I find the date of the first Monday of a given week?
396,913
26
2008-12-29T00:42:56Z
396,926
33
2008-12-29T01:05:22Z
[ "python", "datetime" ]
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week? Many thanks
``` >>> import time >>> time.asctime(time.strptime('2008 50 1', '%Y %W %w')) 'Mon Dec 15 00:00:00 2008' ``` Assuming the first day of your week is Monday, use `%U` instead of `%W` if the first day of your week is Sunday. See the documentation for [strptime](http://docs.python.org/library/time.html#time.strptime) for details. **Update:** Fixed week number. The `%W` directive is 0-based so week 51 would be entered as 50, not 51.
In Python, how do I find the date of the first Monday of a given week?
396,913
26
2008-12-29T00:42:56Z
396,927
8
2008-12-29T01:05:54Z
[ "python", "datetime" ]
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week? Many thanks
This seems to work, assuming week one can have a Monday falling on a day in the last year. ``` from datetime import date, timedelta def get_first_dow(year, week): d = date(year, 1, 1) d = d - timedelta(d.weekday()) dlt = timedelta(days = (week - 1) * 7) return d + dlt ```
In Python, how do I find the date of the first Monday of a given week?
396,913
26
2008-12-29T00:42:56Z
1,287,862
28
2009-08-17T13:07:00Z
[ "python", "datetime" ]
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week? Many thanks
PEZ's and Gerald Kaszuba's solutions work under assumption that January 1st will always be in the first week of a given year. This assumption is not correct for ISO calendar, see [Python's docs](http://docs.python.org/library/datetime.html#datetime.date.isocalendar) for reference. For example, in ISO calendar, week 1 of 2010 actually starts on Jan 4, and Jan 1 of 2010 is in week 53 of 2009. An ISO calendar-compatible solution: ``` from datetime import date, timedelta def week_start_date(year, week): d = date(year, 1, 1) delta_days = d.isoweekday() - 1 delta_weeks = week if year == d.isocalendar()[0]: delta_weeks -= 1 delta = timedelta(days=-delta_days, weeks=delta_weeks) return d + delta ```
In Python, how do I find the date of the first Monday of a given week?
396,913
26
2008-12-29T00:42:56Z
3,314,360
12
2010-07-22T23:36:23Z
[ "python", "datetime" ]
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week? Many thanks
``` from datetime import date, timedelta def first_monday(year, week): d = date(year, 1, 4) # The Jan 4th must be in week 1 according to ISO return d + timedelta(weeks=(week-1), days=-d.weekday()) ```
Confusing [...] List in Python: What is it?
397,034
16
2008-12-29T02:46:31Z
397,054
23
2008-12-29T03:02:35Z
[ "python", "recursion", "list", "recursive-datastructures" ]
So I was writing up a simple binary tree in Python and came across [...] I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however ``` >>> a [[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0] >>> Keys(a)#With a+b [0, 1, 6, 8, 3, -4] >>> Keys(a)#With [a,b] [8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]] >>> Keys(a)[1]#?? [8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]] ``` Version using a+b ``` def Keys(x,y=[]): if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess return y ``` version using [a,b] ``` def Keys(x,y=[]): if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)] return y ``` So what exactly is [...]?
It can also appear if you have a circular structure with a list pointing to itself. Like this: ``` >>> a = [1,2] >>> a.append(a) >>> a [1, 2, [...]] >>> ``` Since python can't print out the structure (it would be an infinite loop) it uses the ellipsis to show that there is recursion in the structure. --- I'm not quite sure if the question was what what going on or how to fix it, but I'll try to correct the functions above. In both of them, you first make two recursive calls, which add data to the list `y`, and then AGAIN append the returned data to `y`. This means the same data will be present several times in the result. Either just collect all the data without adding to any `y`, with something like ``` return [x[2]]+keys(x[0])+keys(x[1]) ``` or just do the appending in the calls, with something like ``` y += [x[2]] keys(x[0], y) #Add left children to y... keys(x[1], y) #Add right children to y... return y ``` (Of course, both these snippets need handling for empty lists etc) @Abgan also noted that you really don't want `y=[]` in the initializer.
Reading the target of a .lnk file in Python?
397,125
16
2008-12-29T04:31:27Z
397,147
7
2008-12-29T04:53:05Z
[ "python", "directory", "shortcut", "target", "lnk" ]
I'm trying to read the target file/directory of a shortcut (`.lnk`) file from Python. Is there a headache-free way to do it? The [.lnk spec [PDF]](http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf) is way over my head. I don't mind using Windows-only APIs. My ultimate goal is to find the `"(My) Videos"` folder on Windows XP and Vista. On XP, by default, it's at `%HOMEPATH%\My Documents\My Videos`, and on Vista it's `%HOMEPATH%\Videos`. However, the user can relocate this folder. In the case, the `%HOMEPATH%\Videos` folder ceases to exists and is replaced by `%HOMEPATH%\Videos.lnk` which points to the new `"My Videos"` folder. And I want its absolute location.
Alternatively, you could try using [SHGetFolderPath()](http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx). The following code might work, but I'm not on a Windows machine right now so I can't test it. ``` import ctypes shell32 = ctypes.windll.shell32 # allocate MAX_PATH bytes in buffer video_folder_path = ctypes.create_string_buffer(260) # 0xE is CSIDL_MYVIDEO # 0 is SHGFP_TYPE_CURRENT # If you want a Unicode path, use SHGetFolderPathW instead if shell32.SHGetFolderPathA(None, 0xE, None, 0, video_folder_path) >= 0: # success, video_folder_path now contains the correct path else: # error ```
Reading the target of a .lnk file in Python?
397,125
16
2008-12-29T04:31:27Z
571,573
23
2009-02-20T22:59:37Z
[ "python", "directory", "shortcut", "target", "lnk" ]
I'm trying to read the target file/directory of a shortcut (`.lnk`) file from Python. Is there a headache-free way to do it? The [.lnk spec [PDF]](http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf) is way over my head. I don't mind using Windows-only APIs. My ultimate goal is to find the `"(My) Videos"` folder on Windows XP and Vista. On XP, by default, it's at `%HOMEPATH%\My Documents\My Videos`, and on Vista it's `%HOMEPATH%\Videos`. However, the user can relocate this folder. In the case, the `%HOMEPATH%\Videos` folder ceases to exists and is replaced by `%HOMEPATH%\Videos.lnk` which points to the new `"My Videos"` folder. And I want its absolute location.
**Create a shortcut using Python (via WSH)** ``` import sys import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut("t:\\test.lnk") shortcut.Targetpath = "t:\\ftemp" shortcut.save() ``` **Read the Target of a Shortcut using Python (via WSH)** ``` import sys import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut("t:\\test.lnk") print(shortcut.Targetpath) ```
Why doesn't Python have multiline comments?
397,148
194
2008-12-29T04:53:17Z
397,159
27
2008-12-29T05:04:11Z
[ "python", "comments", "multiline" ]
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example, ``` """Hello, I am a multiline comment""" ``` and ``` '''Hello, I am a multiline comment''' ``` But technically speaking these are strings, correct? I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /\* \*/ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
This likely goes back to the core concept that there should be one obvious way to do a task. Additional comment styles add unnecessary complications and could decrease readability.
Why doesn't Python have multiline comments?
397,148
194
2008-12-29T04:53:17Z
397,160
11
2008-12-29T05:05:00Z
[ "python", "comments", "multiline" ]
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example, ``` """Hello, I am a multiline comment""" ``` and ``` '''Hello, I am a multiline comment''' ``` But technically speaking these are strings, correct? I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /\* \*/ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
Well, the triple-quotes are used as multiline comments in docstrings. And # comments are used as inline comments and people get use to it. Most of script languages don't have multiline comments either. Maybe that's the cause? See [PEP 0008](http://www.python.org/dev/peps/pep-0008/), section *Comments* And see if your Python editor offers some keyboard shortcut for block commenting. Emacs supports it, as well as Eclipse, presumably most of decent IDEs does.
Why doesn't Python have multiline comments?
397,148
194
2008-12-29T04:53:17Z
397,161
223
2008-12-29T05:06:00Z
[ "python", "comments", "multiline" ]
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example, ``` """Hello, I am a multiline comment""" ``` and ``` '''Hello, I am a multiline comment''' ``` But technically speaking these are strings, correct? I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /\* \*/ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments". Guido has [tweeted](https://twitter.com/gvanrossum/status/112670605505077248) about this, > Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
Why doesn't Python have multiline comments?
397,148
194
2008-12-29T04:53:17Z
397,786
31
2008-12-29T14:16:05Z
[ "python", "comments", "multiline" ]
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example, ``` """Hello, I am a multiline comment""" ``` and ``` '''Hello, I am a multiline comment''' ``` But technically speaking these are strings, correct? I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /\* \*/ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
Triple-quoted text should NOT be considered multi-line comments; by convention, they are [docstrings](http://www.python.org/dev/peps/pep-0257/#rationale). They should describe what your code does and how to use it, but not for things like commenting out blocks of code. According to Guido, [multiline comments in Python are just contiguous single-line comments](http://www.python.org/dev/peps/pep-0008/) (search for "block comments"). To comment blocks of code, I sometimes use the following pattern: ``` if False: # A bunch of code ```
Why doesn't Python have multiline comments?
397,148
194
2008-12-29T04:53:17Z
397,950
59
2008-12-29T15:44:08Z
[ "python", "comments", "multiline" ]
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example, ``` """Hello, I am a multiline comment""" ``` and ``` '''Hello, I am a multiline comment''' ``` But technically speaking these are strings, correct? I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /\* \*/ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
Multi-line comments are easily breakable. What if you have the following in a simple calculator program? ``` operation = '' print("Pick an operation: +-*/") # Get user input here ``` Try to comment that with a multi-line comment: ``` /* operation = '' print("Pick an operation: +-*/") # Get user input here */ ``` Oops, your string contains the end comment delimiter.
Why doesn't Python have multiline comments?
397,148
194
2008-12-29T04:53:17Z
398,025
8
2008-12-29T16:18:23Z
[ "python", "comments", "multiline" ]
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example, ``` """Hello, I am a multiline comment""" ``` and ``` '''Hello, I am a multiline comment''' ``` But technically speaking these are strings, correct? I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /\* \*/ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
From [The Zen of Python](http://www.python.org/dev/peps/pep-0020/): There should be one-- and preferably only one --obvious way to do it.
Split by \b when your regex engine doesn't support it
398,560
4
2008-12-29T20:22:14Z
398,584
9
2008-12-29T20:38:26Z
[ "python", "regex" ]
How can I split by word boundary in a regex engine that doesn't support it? python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation. example input: ``` "hello, foo" ``` expected output: ``` ['hello', ', ', 'foo'] ``` actual python output: ``` >>> re.compile(r'\b').split('hello, foo') ['hello, foo'] ```
(\W+) can give you the expected output: ``` >>> re.compile(r'(\W+)').split('hello, foo') ['hello', ', ', 'foo'] ```
Why can't I subclass datetime.date?
399,022
15
2008-12-29T23:08:18Z
400,583
31
2008-12-30T15:36:32Z
[ "python", "oop", "datetime", "subclass" ]
Why doesn't the following work (Python 2.5.2)? ``` >>> import datetime >>> class D(datetime.date): def __init__(self, year): datetime.date.__init__(self, year, 1, 1) >>> D(2008) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function takes exactly 3 arguments (1 given) ``` I wanted to create a class that was just like `datetime.date`, but with a different `__init__` function. Apparently my function never gets called. Instead the original `datetime.date.__init__` is called and fails because that expects 3 arguments and I am passing in one. What's going on here? And is this a clue? ``` >>> datetime.date.__init__ <slot wrapper '__init__' of 'object' objects> ``` Thanks!
Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The `__init__` method does nothing because they are *immutable* objects, therefore the constructor (`__new__`) should do all the work. You would see the same behavior subclassing int, str, etc. ``` >>> import datetime >>> class D(datetime.date): def __new__(cls, year): return datetime.date.__new__(cls, year, 1, 1) >>> D(2008) D(2008, 1, 1) ```
Why can't I subclass datetime.date?
399,022
15
2008-12-29T23:08:18Z
402,024
8
2008-12-31T01:19:50Z
[ "python", "oop", "datetime", "subclass" ]
Why doesn't the following work (Python 2.5.2)? ``` >>> import datetime >>> class D(datetime.date): def __init__(self, year): datetime.date.__init__(self, year, 1, 1) >>> D(2008) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function takes exactly 3 arguments (1 given) ``` I wanted to create a class that was just like `datetime.date`, but with a different `__init__` function. Apparently my function never gets called. Instead the original `datetime.date.__init__` is called and fails because that expects 3 arguments and I am passing in one. What's going on here? And is this a clue? ``` >>> datetime.date.__init__ <slot wrapper '__init__' of 'object' objects> ``` Thanks!
Please read the Python reference on [*Data model*](http://www.python.org/doc/current/reference/datamodel.html), especially about the `__new__` [special method](http://www.python.org/doc/current/reference/datamodel.html#object.__new__). Excerpt from that page (my italics): > `__new__()` is intended mainly to allow subclasses of *immutable* types (like int, str, or tuple) to *customize instance creation*. It is also commonly overridden in custom metaclasses in order to customize class creation. `datetime.datetime` is also an immutable type. PS If you think that: * an object implemented in C cannot be subclassed, or * `__init__` doesn't get called for C implemented objects, only `__new__` then please try it: ``` >>> import array >>> array <module 'array' (built-in)> >>> class A(array.array): def __init__(self, *args): super(array.array, self).__init__(*args) print "init is fine for objects implemented in C" >>> a=A('c') init is fine for objects implemented in C >>> ```
Failing to send email with the Python example
399,129
18
2008-12-29T23:51:33Z
399,240
25
2008-12-30T00:48:19Z
[ "python", "email", "smtplib" ]
I've been trying (and failing) to figure out how to send email via Python. Trying the example from here: <http://docs.python.org/library/smtplib.html#smtplib.SMTP> but added the line `server = smtplib.SMTP_SSL('smtp.gmail.com', 465)` after I got a bounceback about not having an SSL connection. Now I'm getting this: ``` Traceback (most recent call last): File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module> server = smtplib.SMTP('smtp.gmail.com', 65) File "C:\Python26\lib\smtplib.py", line 239, in __init__ (code, msg) = self.connect(host, port) File "C:\Python26\lib\smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python26\lib\smtplib.py", line 273, in _get_socket return socket.create_connection((port, host), timeout) File "C:\Python26\lib\socket.py", line 512, in create_connection raise error, msg error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond >>> ``` Thoughts? --- server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] \_ssl.c:480: error:140770FC:SSL routines:SSL23\_GET\_SERVER\_HELLO:unknown protocol" (see below). I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake. " ``` import smtplib mailuser = '[email protected]' mailpasswd = 'MYPASSWORD' fromaddr = '[email protected]' toaddrs = '[email protected]' msg = 'Hooooorah!' print msg server = smtplib.SMTP_SSL('smtp.google.com') server = smtplib.SMTP_SSL_PORT=587 server.user(mailuser) server.pass_(mailpasswd) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() ``` " and then I get this error message: " ``` Traceback (most recent call last): File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module> server = smtplib.SMTP_SSL('smtp.google.com') File "C:\Python26\lib\smtplib.py", line 749, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout) File "C:\Python26\lib\smtplib.py", line 239, in __init__ (code, msg) = self.connect(host, port) File "C:\Python26\lib\smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python26\lib\smtplib.py", line 755, in _get_socket self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) File "C:\Python26\lib\ssl.py", line 350, in wrap_socket suppress_ragged_eofs=suppress_ragged_eofs) File "C:\Python26\lib\ssl.py", line 118, in __init__ self.do_handshake() File "C:\Python26\lib\ssl.py", line 293, in do_handshake self._sslobj.do_handshake() SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol ``` " note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP *underscore* SSL *underscore* PORT=587", there's some sort of formatting thing going on here.
The following code works for me: ``` import smtplib FROMADDR = "[email protected]" LOGIN = FROMADDR PASSWORD = "my.real.password" TOADDRS = ["[email protected]"] SUBJECT = "Test" msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (FROMADDR, ", ".join(TOADDRS), SUBJECT) ) msg += "some text\r\n" server = smtplib.SMTP('smtp.gmail.com', 587) server.set_debuglevel(1) server.ehlo() server.starttls() server.login(LOGIN, PASSWORD) server.sendmail(FROMADDR, TOADDRS, msg) server.quit() ``` I'm using Python 2.5.2. **Edit**: changed port from 25 to 587 as suggested by ΤΖΩΤΖΙΟΥ, and dropped the second ehlo(). Now I would love to know why port 25 works *perfectly* from my machine (and port 465 does *not*).
How to integrate pep8.py in Eclipse?
399,956
82
2008-12-30T10:39:53Z
2,296,249
23
2010-02-19T12:36:16Z
[ "python", "eclipse", "pydev", "pep8" ]
A little background: * [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow. * [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to PEP 8. * [Eclipse](http://www.eclipse.org/) is a great IDE. With the [Pydev](http://pydev.sourceforge.net/) extension, it that can be used to develop Python I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse. It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings. Maybe there is an obvious way to do it, but I haven't found it yet. Question is: **How to integrate pep8.py in Eclipse?**
I don't know how to integrate it for whole project, but I have used it as an external tool to analyze an individual file. Note that the [`pycodestyle`](https://pypi.python.org/pypi/pycodestyle/) package is the official replacement for and is the newer version of the [`pep8`](https://pypi.python.org/pypi/pep8/) package. To install it, run: ``` $ sudo pip install --upgrade pycodestyle ``` Next, in Eclipse: 1. Select **Run-External Tools-External Tools Configurations...** 2. Select **Program** root node. 3. Press **New launch configuration** button. 4. Enter **Name** for your launch configuration. I use `pycodestyle`. 5. Fill following fields: **Location** -- `${system_path:pycodestyle}` **Working directory** -- `${container_loc}` **Arguments** -- `"${resource_name}"` (This uses the currently active file.) Go to **Common** tab and confirm that the **Allocate Console** checkbox is checked. A benefit of this approach is that you can use a very up-to-date version of the package, and are not limited to the old version included with PyDev. And if you are curious about setting up `pylint` in a similar manner, see [this answer](https://stackoverflow.com/a/39863131/832230).
How to integrate pep8.py in Eclipse?
399,956
82
2008-12-30T10:39:53Z
8,532,188
75
2011-12-16T09:32:19Z
[ "python", "eclipse", "pydev", "pep8" ]
A little background: * [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow. * [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to PEP 8. * [Eclipse](http://www.eclipse.org/) is a great IDE. With the [Pydev](http://pydev.sourceforge.net/) extension, it that can be used to develop Python I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse. It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings. Maybe there is an obvious way to do it, but I haven't found it yet. Question is: **How to integrate pep8.py in Eclipse?**
As of PyDev 2.3.0, `pep8` is integrated in PyDev by default, even shipping with a default version of it. Open Window > Preferences It must be enabled in PyDev > Editor > Code Analysis > pep8.py Errors/Warnings should be shown as markers (as other things in the regular code analysis). In the event a file is not analyzed, see <https://stackoverflow.com/a/31001619/832230>.
How to integrate pep8.py in Eclipse?
399,956
82
2008-12-30T10:39:53Z
8,830,316
10
2012-01-12T04:55:42Z
[ "python", "eclipse", "pydev", "pep8" ]
A little background: * [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow. * [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to PEP 8. * [Eclipse](http://www.eclipse.org/) is a great IDE. With the [Pydev](http://pydev.sourceforge.net/) extension, it that can be used to develop Python I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse. It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings. Maybe there is an obvious way to do it, but I haven't found it yet. Question is: **How to integrate pep8.py in Eclipse?**
1. Open your Eclipse 2. Go to Help and select Install New Software 3. Click the Add button and a "Add Repository" Dialog box will appear 4. You can use any name you like for it. (I used PyDev) 5. For the location, enter "http://pydev.org/updates" 6. Click Ok. 7. You are now in the process of installation. Just wait for it to finish. 8. After the installation, close Eclipse and Open it again. 9. Now that PyDev is installed in your Eclipse, go to Window->Preferences 10. Choose PyDev->Editor->Code Analysis 11. Go to pep8.py tab 12. Choose the radio button for warning and click Ok. That's it. Your Eclipse IDE is now integrated with PEP8. To run pep8.py automatically, right click on your project editor. Choose PyDev and click "code analysis". In your problems tab in your workspace, you will see warnings that points to the line that you have made a violation in the PEP8 (if you have violated).
Ignoring XML errors in Python
399,980
5
2008-12-30T10:48:33Z
399,996
10
2008-12-30T10:57:54Z
[ "python", "xml", "minidom" ]
I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser. Is it possible to ignore them, like a browser for example? I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.
There is a library called [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), I think it's what you're looking for. As you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML. > Beautiful Soup is a Python HTML/XML > parser designed for quick turnaround > projects like screen-scraping. Three > features make it powerful: > > 1. Beautiful Soup won't choke if you give it bad markup. It yields a > parse tree that makes approximately as > much sense as your original document. > This is usually good enough to collect > the data you need and run away. > 2. Beautiful Soup provides a few simple methods and Pythonic idioms for > navigating, searching, and modifying a > parse tree: a toolkit for dissecting a > document and extracting what you need. > You don't have to create a custom > parser for each application. > 3. Beautiful Soup automatically converts incoming documents to Unicode > and outgoing documents to UTF-8. You > don't have to think about encodings, > unless the document doesn't specify an > encoding and Beautiful Soup can't > autodetect one. Then you just have to > specify the original encoding. > > Beautiful Soup parses anything you > give it, and does the tree traversal > stuff for you. You can tell it "Find > all the links", or "Find all the links > of class externalLink", or "Find all > the links whose urls match "foo.com", > or "Find the table heading that's got > bold text, then give me that text."
How do you get Python to write down the code of a function it has in memory?
399,991
4
2008-12-30T10:55:43Z
400,040
12
2008-12-30T11:18:39Z
[ "python", "artificial-intelligence" ]
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machine and no one else has access to it, it is secure in a trivial way. I can also write a similar file very easily: ``` def writeoptions(directory): options="" options+="starting_length=%s%s"%(starting_length,os.linesep) options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep) options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep) ... open("%s%soptions.py"%(directory,os.sep),'w').write(options) ``` I want to pass a function as one of the parameters: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 def pippo(a,b): return a+b functionoperator=pippo ``` And of course in the real experiment the function pippo will be much more complex. And different from experiment to experiment. But what I am unable to do is to write the function automatically. In short I don't know how to generalise the writeoptions function to keep on writing the options, if one of the options is a function. I could of course copy the original file, but this is inelegant, inefficient (because it contains a lot of extra options that are not being used), and generally does not solve the question. How do you get python to write down the code of a function, as it writes down the value of a variable?
``` vinko@mithril$ more a.py def foo(a): print a vinko@mithril$ more b.py import a import inspect a.foo(89) print inspect.getsource(a.foo) vinko@mithril$ python b.py 89 def foo(a): print a ```
Reading and running a mathematical expression in Python
400,050
5
2008-12-30T11:22:43Z
400,081
7
2008-12-30T11:43:43Z
[ "python" ]
Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? Aside from grabbing a string, file or url I have no idea of where to start with this.
Because python supports some algebraic forms, you could do: ``` eval("1 + 1") ``` But this allows the input to execute about anything defined in your env: ``` eval("__import__('sys').exit(1)") ``` Also, if you want to support something python doesn't support, the approach fails: ``` x³ + y² + c ----------- = 0 z ``` Instead of doing this, you can implement a tokenizer and a parser with [ply](http://www.dabeaz.com/ply/). Evaluating a thing like '1 + 1' ought not take more than ten lines or so. You could also implement the tokenizer and the parser by hand. Read about LL and LR parsers. Before attempting this it's also better to learn using parser generators first.
Resize image in Python without losing EXIF data
400,788
23
2008-12-30T16:42:02Z
400,838
12
2008-12-30T17:00:10Z
[ "python", "image-processing", "python-imaging-library", "exif" ]
I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this: ``` img = Image.open('foo.jpg') width,height = 800,600 if img.size[0] < img.size[1]: width,height = height,width resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter resized_img.save('foo-resized.jpg') ``` Any ideas? Or other libraries that I could be using?
``` import jpeg jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg') ``` <http://www.emilas.com/jpeg/>
Resize image in Python without losing EXIF data
400,788
23
2008-12-30T16:42:02Z
4,270,949
10
2010-11-24T19:57:13Z
[ "python", "image-processing", "python-imaging-library", "exif" ]
I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this: ``` img = Image.open('foo.jpg') width,height = 800,600 if img.size[0] < img.size[1]: width,height = height,width resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter resized_img.save('foo-resized.jpg') ``` Any ideas? Or other libraries that I could be using?
You can use pyexiv2 to copy EXIF data from source image. In the following example image is resized using PIL library, EXIF data copied with pyexiv2 and image size EXIF fields are set with new size. ``` def resize_image(source_path, dest_path, size): # resize image image = Image.open(source_path) image.thumbnail(size, Image.ANTIALIAS) image.save(dest_path, "JPEG") # copy EXIF data source_image = pyexiv2.Image(source_path) source_image.readMetadata() dest_image = pyexiv2.Image(dest_path) dest_image.readMetadata() source_image.copyMetadataTo(dest_image) # set EXIF image size info to resized size dest_image["Exif.Photo.PixelXDimension"] = image.size[0] dest_image["Exif.Photo.PixelYDimension"] = image.size[1] dest_image.writeMetadata() # resizing local file resize_image("41965749.jpg", "resized.jpg", (600,400)) ```
Resize image in Python without losing EXIF data
400,788
23
2008-12-30T16:42:02Z
22,063,878
7
2014-02-27T09:13:16Z
[ "python", "image-processing", "python-imaging-library", "exif" ]
I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this: ``` img = Image.open('foo.jpg') width,height = 800,600 if img.size[0] < img.size[1]: width,height = height,width resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter resized_img.save('foo-resized.jpg') ``` Any ideas? Or other libraries that I could be using?
There is actually a really simple way of copying EXIF data from a picture to another with only PIL. Though it doesn't permit to modify the exif tags. ``` image = Image.open('test.jpg') exif = image.info['exif'] # Your picture process here image = image.rotate(90) image.save('test_rotated.jpg', 'JPEG', exif=exif) ``` As you can see, the save function can take the exif argument which permits to copy the raw exif data in the new image when saving. You don't actually need any other lib if that's all you want to do. I can't seem to find any documentation on the save options and I don't even know if that's specific to Pillow or working with PIL too. (If someone has some kind of link, I would enjoy if they posted it in the comments)
Define css class in django Forms
401,025
125
2008-12-30T18:18:41Z
401,030
66
2008-12-30T18:20:28Z
[ "python", "django", "forms", "newforms" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form.
Answered my own question. *Sigh* <http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs> I didn't realize it was passed into the widget constructor.
Define css class in django Forms
401,025
125
2008-12-30T18:18:41Z
401,057
59
2008-12-30T18:32:11Z
[ "python", "django", "forms", "newforms" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form.
Here is another solution for adding class definitions to the widgets after declaring the fields in the class. ``` def __init__(self, *args, **kwargs): super(SampleClass, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs['class'] = 'my_class' ```
Define css class in django Forms
401,025
125
2008-12-30T18:18:41Z
4,272,671
23
2010-11-25T00:06:15Z
[ "python", "django", "forms", "newforms" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form.
Expanding on the method pointed to at docs.djangoproject.com: ``` class MyForm(forms.Form): comment = forms.CharField( widget=forms.TextInput(attrs={'size':'40'})) ``` I thought it was troublesome to have to know the native widget type for every field, and thought it funny to override the default just to put a class name on a form field. This seems to work for me: ``` class MyForm(forms.Form): #This instantiates the field w/ the default widget comment = forms.CharField() #We only override the part we care about comment.widget.attrs['size'] = '40' ``` This seems a little cleaner to me.
Define css class in django Forms
401,025
125
2008-12-30T18:18:41Z
4,667,831
13
2011-01-12T10:42:45Z
[ "python", "django", "forms", "newforms" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form.
Here is Simple way to alter in view. add below in view just before passing it into template. ``` form = MyForm(instance = instance.obj) form.fields['email'].widget.attrs = {'class':'here_class_name'} ```
Define css class in django Forms
401,025
125
2008-12-30T18:18:41Z
4,676,071
128
2011-01-13T01:56:34Z
[ "python", "django", "forms", "newforms" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form.
Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: [django-widget-tweaks](https://github.com/kmike/django-widget-tweaks). Hope somebody will find it useful.
Define css class in django Forms
401,025
125
2008-12-30T18:18:41Z
18,962,481
26
2013-09-23T14:55:01Z
[ "python", "django", "forms", "newforms" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form.
This can be done using a custom template filter. considering you render your form this way : ``` <form action="/contact/" method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="id_subject">Email subject:</label> {{ form.subject }} </div> </form> ``` form.subject is an instance of [BoundField](https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.BoundField) which has the **as\_widget** method. you can create a custom filter "addcss" in "my\_app/templatetags/myfilters.py" ``` from django import template register = template.Library() @register.filter(name='addcss') def addcss(value, arg): return value.as_widget(attrs={'class': arg}) ``` And then apply your filter: ``` {% load myfilters %} <form action="/contact/" method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="id_subject">Email subject:</label> {{ form.subject|addcss:'MyClass' }} </div> </form> ``` form.subjects will then be rendered with the "MyClass" css class. Hope this help.
Define css class in django Forms
401,025
125
2008-12-30T18:18:41Z
20,573,612
12
2013-12-13T18:35:43Z
[ "python", "django", "forms", "newforms" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form.
If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from `forms.ModelForm`, and then inherit from it ``` class BaseForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'someClass' class WhateverForm(BaseForm): class Meta: model = SomeModel ``` This helped me to add the `'form-control'` class to all of the fields on all of the forms of my application automatically, without adding replication of code.
Naming Python loggers
401,277
44
2008-12-30T19:47:53Z
402,471
63
2008-12-31T07:31:40Z
[ "python", "django", "logging" ]
In Django, I've got loggers all over the place, currently with hard-coded names. For module-level logging (i.e., in a module of view functions) I have the urge to do this. ``` log = logging.getLogger(__name__) ``` For class-level logging (i.e., in a class `__init__` method) I have the urge to do this. ``` self.log = logging.getLogger("%s.%s" % ( self.__module__, self.__class__.__name__)) ``` I'm looking for second opinions before I tackle several dozen occurrences of `getLogger("hard.coded.name")`. Will this work? Anyone else naming their loggers with the same unimaginative ways? Further, should I break down and write a class decorator for this log definition?
I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple: ``` import logging LOG = logging.getLogger(__name__) ``` At the top of the module and subsequent: ``` LOG.info('Spam and eggs are tasty!') ``` from anywhere in the file typically gets me to where I want to be. This avoids the need for `self.log` all over the place, which tends to bother me from both a put-it-in-every-class perspective and makes me 5 characters closer to 79 character lines that fit. You could always use a pseudo-class-decorator: ``` >>> import logging >>> class Foo(object): ... def __init__(self): ... self.log.info('Meh') ... >>> def logged_class(cls): ... cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__)) ... >>> logged_class(Foo) >>> logging.basicConfig(level=logging.DEBUG) >>> f = Foo() INFO:__main__.Foo:Meh ```
Scaling the y-axis with Matplotlib in Python
401,787
4
2008-12-30T23:02:08Z
401,823
7
2008-12-30T23:21:52Z
[ "python", "matplotlib" ]
How to scale the y-axis with [Matplotlib](http://matplotlib.sourceforge.net/)? I don't want to change the y-limit, I just want to extend the physical space. ``` ^ ^ | | | | +----> | Before +----> After ```
Just use a larger height value when you instantiate the figure: ``` from pylab import * x = linspace(0, 10*pi, 2**10) y = sin(x) figure(figsize=(5, 10)) plot(x, y) show() ``` Where `figsize=(width, height)` and defaults to `(8, 6)`. Values are in inches (the `dpi` keyword arg can be used to define the [DPI](http://en.wikipedia.org/wiki/Dots_per_inch) for the figure, and there's a default value in your `matplotlibrc` file) For a figure already created, I believe there is a `set_size_inches(width, height)` method.
How to store a dictionary on a Django Model?
402,217
32
2008-12-31T03:18:15Z
402,248
13
2008-12-31T03:39:18Z
[ "python", "django", "orm", "persistence" ]
I need to store some data in a Django model. These data are not equal to all instances of the model. At first I thought about subclassing the model, but I’m trying to keep the application flexible. If I use subclasses, I’ll need to create a whole class each time I need a new kind of object, and that’s no good. I’ll also end up with a lot of subclasses only to store a pair of extra fields. I really feel that a dictionary would be the best approach, but there’s nothing in the Django documentation about storing a dictionary in a Django model (or I can’t find it). Any clues?
If you don't need to query by any of this extra data, then you can store it as a serialized dictionary. Use `repr` to turn the dictionary into a string, and `eval` to turn the string back into a dictionary. Take care with eval that there's no user data in the dictionary, or use a safe\_eval implementation.
How to store a dictionary on a Django Model?
402,217
32
2008-12-31T03:18:15Z
402,526
22
2008-12-31T08:19:28Z
[ "python", "django", "orm", "persistence" ]
I need to store some data in a Django model. These data are not equal to all instances of the model. At first I thought about subclassing the model, but I’m trying to keep the application flexible. If I use subclasses, I’ll need to create a whole class each time I need a new kind of object, and that’s no good. I’ll also end up with a lot of subclasses only to store a pair of extra fields. I really feel that a dictionary would be the best approach, but there’s nothing in the Django documentation about storing a dictionary in a Django model (or I can’t find it). Any clues?
If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the container instance. Something like: ``` class Dicty(models.Model): name = models.CharField(max_length=50) class KeyVal(models.Model): container = models.ForeignKey(Dicty, db_index=True) key = models.CharField(max_length=240, db_index=True) value = models.CharField(max_length=240, db_index=True) ``` It's not pretty, but it'll let you access/search the innards of the dictionary using the DB whereas a pickle/serialize solution will not.
How do you uninstall a python package that was installed using distutils?
402,359
72
2008-12-31T05:26:14Z
402,444
34
2008-12-31T07:00:04Z
[ "python" ]
Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?
It varies based on the options that you pass to `install` and the contents of the [distutils configuration files](http://docs.python.org/install/index.html#inst-config-files) on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways. Notably, [distutils does not have an uninstall command](http://bugs.python.org/issue4673) at this time. It's also noteworthy that deleting a package/egg can cause dependency issues -- utilities like [`easy_install`](http://peak.telecommunity.com/DevCenter/EasyInstall) attempt to alleviate such problems.
How do you uninstall a python package that was installed using distutils?
402,359
72
2008-12-31T05:26:14Z
403,563
12
2008-12-31T17:31:17Z
[ "python" ]
Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?
The three things that get installed that you will need to delete are: 1. Packages/modules 2. Scripts 3. Data files Now on my linux system these live in: 1. /usr/lib/python2.5/site-packages 2. /usr/bin 3. /usr/share But on a windows system they are more likely to be entirely within the Python distribution directory. I have no idea about OSX except it is more likey to follow the linux pattern.
How do you uninstall a python package that was installed using distutils?
402,359
72
2008-12-31T05:26:14Z
405,406
7
2009-01-01T20:06:35Z
[ "python" ]
Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?
Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work. If you want to make it work again, simply re-install. By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.
How do you uninstall a python package that was installed using distutils?
402,359
72
2008-12-31T05:26:14Z
8,471,143
11
2011-12-12T07:27:00Z
[ "python" ]
Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?
Another time stamp based hack: 1. Create an anchor: `touch /tmp/ts` 2. Reinstall the package to be removed: `python setup.py install --prefix=<PREFIX>` 3. Remove files what are more recent than the anchor file: `find <PREFIX> -cnewer /tmp/ts | xargs rm -r`
Help--Function Pointers in Python
402,364
3
2008-12-31T05:34:38Z
402,369
20
2008-12-31T05:41:07Z
[ "python", "function", "pointers" ]
My idea of program: I have a dictionary: ``` options = { 'string' : select_fun(function pointer), 'float' : select_fun(function pointer), 'double' : select_fun(function pointer) } ``` whatever type comes single function `select_fun(function pointer)` gets called. Inside `select_fun(function pointer)`,I will have diff functions for float, double and so on. Depending on function pointers, specified function will get called. I don't know whether my programming knowledge is good or bad, still I need help.
Could you be more specific on what you're trying to do? You don't have to do anything special to get function pointers in Python -- you can pass around functions like regular objects: ``` def plus_1(x): return x + 1 def minus_1(x): return x - 1 func_map = {'+' : plus_1, '-' : minus_1} func_map['+'](3) # returns plus_1(3) ==> 4 func_map['-'](3) # returns minus_1(3) ==> 2 ```
Caching result of setUp() using Python unittest
402,483
7
2008-12-31T07:43:31Z
402,492
14
2008-12-31T07:48:46Z
[ "python", "unit-testing" ]
I currently have a unittest.TestCase that looks like.. ``` class test_appletrailer(unittest.TestCase): def setup(self): self.all_trailers = Trailers(res = "720", verbose = True) def test_has_trailers(self): self.failUnless(len(self.all_trailers) > 1) # ..more tests.. ``` This works fine, but the `Trailers()` call takes about 2 seconds to run.. Given that `setUp()` is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions) What is the correct way of caching the `self.all_trailers` variable between tests? Removing the setUp function, and doing.. ``` class test_appletrailer(unittest.TestCase): all_trailers = Trailers(res = "720", verbose = True) ``` ..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache\_trailers global variable (which works correctly, but is rather horrible): ``` cache_trailers = None class test_appletrailer(unittest.TestCase): def setUp(self): global cache_trailers if cache_trailers is None: cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True) else: self.all_trailers = cache_trailers ```
How about using a class member that only gets initialized once? ``` class test_appletrailer(unittest.TestCase): all_trailers = None def setup(self): # Only initialize all_trailers once. if self.all_trailers is None: self.__class__.all_trailers = Trailers(res = "720", verbose = True) ``` Lookups that refer to `self.all_trailers` will go to the next step in the [MRO](http://www.python.org/download/releases/2.3/mro/) -- `self.__class__.all_trailers`, which will be initialized.
Caching result of setUp() using Python unittest
402,483
7
2008-12-31T07:43:31Z
403,541
8
2008-12-31T17:25:38Z
[ "python", "unit-testing" ]
I currently have a unittest.TestCase that looks like.. ``` class test_appletrailer(unittest.TestCase): def setup(self): self.all_trailers = Trailers(res = "720", verbose = True) def test_has_trailers(self): self.failUnless(len(self.all_trailers) > 1) # ..more tests.. ``` This works fine, but the `Trailers()` call takes about 2 seconds to run.. Given that `setUp()` is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions) What is the correct way of caching the `self.all_trailers` variable between tests? Removing the setUp function, and doing.. ``` class test_appletrailer(unittest.TestCase): all_trailers = Trailers(res = "720", verbose = True) ``` ..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache\_trailers global variable (which works correctly, but is rather horrible): ``` cache_trailers = None class test_appletrailer(unittest.TestCase): def setUp(self): global cache_trailers if cache_trailers is None: cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True) else: self.all_trailers = cache_trailers ```
An alternative to the proposed solution would be to use a more featured test runner like [Nose](http://somethingaboutorange.com/mrl/projects/nose/). With Nose, you can have module-level setup functions which will be run once for a test module. Since it is entirely compatible with unittest, you wouldn't have to change any code. From the Nose manual: > nose supports fixtures at the package, > module, class, and test case level, **so** > **expensive initialization can be done** > **as infrequently as possible**. Fixtures are [described in detail here](http://somethingaboutorange.com/mrl/projects/nose/#fixtures). Of course, apart from fulfilling your use-case, I can also strongly recommend it as a general testing tool. None of my projects will leave home without it.
How to determine the variable type in Python?
402,504
607
2008-12-31T07:58:57Z
402,507
172
2008-12-31T08:02:04Z
[ "python", "types", "unsigned", "signed", "16-bit" ]
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.? How do I view it?
You may be looking for the `type()` function. See the examples below, but there's no "unsigned" type in Python just like Java. Positive integer: ``` >>> v = 10 >>> type(v) <type 'int'> ``` *Large* positive integer: ``` >>> v = 100000000000000 >>> type(v) <type 'long'> ``` Negative integer: ``` >>> v = -10 >>> type(v) <type 'int'> ``` Literal sequence of characters: ``` >>> v = 'hi' >>> type(v) <type 'str'> ```