title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How can I read all availably data from subprocess.Popen.stdout (non blocking)?
3,076,542
14
2010-06-19T17:34:50Z
3,078,292
10
2010-06-20T05:11:16Z
[ "python", "subprocess" ]
I need a way to either read all currently available characters in stream created by Popen or to find out how many characters are left in the buffer. Backround: I want to remote control an interactive application in Python. So far I used Popen to create a new subprocess: ``` process=subprocess.Popen(["python"],shell=T...
Incremental parsing of Popen's stdout is not a problem really. Just insert a pipe into a thread and have it scrub through output, looking for delimiters. Depending on your preference, it can pipe it into another pipe / file-like or put the parsed "chunks" on the "stack" in asynchronous mode. Here is an example of async...
What is the difference between these two solutions - lambda or loop - Python
3,076,692
7
2010-06-19T18:19:58Z
3,076,698
12
2010-06-19T18:21:39Z
[ "python" ]
I want to calculate the sum of even numbers within a domain. I have two solutions, but I'm not sure of the advantages/disadvantages of each. Which is the optimal solution? ``` import sys domain = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Cal1 = sum(filter(lambda n : n % 2 == 0, domain)) Cal2 = sum([n for n in domain if n % 2 ==...
The second really should be just a generator, not a list comprehension (since you don't actually need to create a list to be able to sum the output of a generator): ``` Cal2 = sum(n for n in domain if n % 2 == 0) ``` It's the now-preferred ("pythonic") way for accomplishing this task. * Using a list comprehension (t...
Python: Is this an ok way of overriding __eq__ and __hash__?
3,076,967
17
2010-06-19T19:41:33Z
3,076,987
13
2010-06-19T19:46:53Z
[ "python", "hash", "code-review" ]
I'm new to Python, and I wanted to make sure that I overrode `__eq__` and `__hash__` correctly, so as not to cause painful errors later: (I'm using Google App Engine.) ``` class Course(db.Model): dept_code = db.StringProperty() number = db.IntegerProperty() title = db.StringProperty() raw_pre_reqs = d...
The first one is fine. The second one is problematic for two reasons: 1. there might be duplicates in `.courses` 2. two entities with identical `.courses` but different `.forwardLinks` would compare equal but have different hashes I would fix the second one by making equality depend on both courses and forward links,...
Quoting long strings without newlines in Python
3,076,979
9
2010-06-19T19:45:09Z
3,076,998
18
2010-06-19T19:50:48Z
[ "python" ]
I am trying to write a long string in Python that gets displayed as the help item of an OptParser option. In my source code .py file, I'd like to place newlines so that my code doesn't spend new lines. However, I don't want those newlines to affect how that string is displayed when the code is run. For example, I want ...
You can concatenate string literals just like in C, so `"foo" "bar"` is the same as `"foobar"`, meaning this should do what you want: ``` parser.add_option("--my-option", dest="my_option", nargs=2, default=None, help="Here is a long description of my option. It does many things " "but I want the ...
Quoting long strings without newlines in Python
3,076,979
9
2010-06-19T19:45:09Z
3,077,017
9
2010-06-19T19:55:27Z
[ "python" ]
I am trying to write a long string in Python that gets displayed as the help item of an OptParser option. In my source code .py file, I'd like to place newlines so that my code doesn't spend new lines. However, I don't want those newlines to affect how that string is displayed when the code is run. For example, I want ...
Just take advantage of string-literal **juxtaposition** -- in Python, like in C, if two string literals are next to each other with just whitespace in-between (including newlines), the compiler will merge them into a single string literal, ignoring the whitespace. I.e.: ``` parser.add_option("--my-option", dest="my_op...
Fastest way of deleting certain keys from dict in Python
3,077,145
6
2010-06-19T20:35:15Z
3,077,173
9
2010-06-19T20:45:28Z
[ "python", "dictionary", "filter" ]
I'm looking for most fastest/effective way of deleting certain keys in a python dict Here are some options ``` for k in somedict.keys(): if k.startswith("someprefix"): del somedict[k] ``` or ``` dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix')) ``` Logically first snip...
If the dict is large enough, it may make sense to generate a whole new dict instead. ``` dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix')) ```
Fastest way of deleting certain keys from dict in Python
3,077,145
6
2010-06-19T20:35:15Z
3,077,179
10
2010-06-19T20:47:53Z
[ "python", "dictionary", "filter" ]
I'm looking for most fastest/effective way of deleting certain keys in a python dict Here are some options ``` for k in somedict.keys(): if k.startswith("someprefix"): del somedict[k] ``` or ``` dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix')) ``` Logically first snip...
Not only is `del` more easily understood, but it seems slightly faster than [pop()](http://docs.python.org/library/stdtypes.html#dict.pop): ``` $ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}" "for k in d.keys():" " if k.startswith('f'):" " del d[k]" 1000000 loops, best of 3: 0.733 usec per loop $ python -m ti...
Get a layout's widgets in PyQT
3,077,192
4
2010-06-19T20:54:37Z
3,077,307
7
2010-06-19T21:30:09Z
[ "python", "qt", "pyqt", "pyqt4" ]
I have a `QVBoxLayout` that I've added a few widgets to, via `addWidget()`. I need to now delete those widgets, and it seems I need to use `removeWidget()` (which takes in a widget to be removed) to do that. I thought that calling `children()` or `findChildren(QWidget)` on my layout would return a list of the widgets ...
That's odd. My understanding is that adding widgets via `addWidget` transfers ownership to the layout so calling `children()` ought to work. However, as an alternative you could loop over the layout items by using `count()` and `itemAt(int)` to supply a `QLayoutItem` to `removeItem(QLayoutItem*)`. **Edit:** I've jus...
Mercurial/Python - What Does The Underscore Function Do?
3,077,227
5
2010-06-19T21:04:32Z
3,077,234
8
2010-06-19T21:08:05Z
[ "python", "mercurial", "magic-function" ]
In Mercurial, many of the extensions wrap their help/syntax string in a call to an underscore function, like so: ``` _('[OPTION] [QUEUE]') ``` This confuses me, because it does not seem necessary (the [Writing Extensions](http://mercurial.selenic.com/wiki/WritingExtensions) instructions don't mention it) and there d...
Look on line 45: ``` from mercurial.i18n import _ ``` This is the usual abbreviation in the internationalization package [gettext](http://docs.python.org/library/gettext.html), and possibly other packages too, for the function that returns a translation of its argument to the language the program is currently running...
Invoke Django template renderer in memory without any files from strings?
3,077,272
3
2010-06-19T21:19:53Z
3,077,296
8
2010-06-19T21:26:08Z
[ "python", "django", "django-templates" ]
I have built a Macro language for my users that is based upon the Django template language. Users enter into UITextFields their template/macro snippets that can be rendered in the context of larger documents. So I have large multi-line string snippets of django template code that should be populated with variables that...
``` from django.template import Context, Template template = Template("this is a template string! {{ foo }}") c = Context({"foo": "barbarbar"}) print template.render(c) ```
Connecting to a host listed in ~/.ssh/config when using Fabric
3,077,281
71
2010-06-19T21:21:23Z
5,674,196
9
2011-04-15T08:30:23Z
[ "python", "ssh", "fabric" ]
I'm having trouble with [`Fabric`](http://docs.fabfile.org/0.9.1/api/contrib/project.html) not recognizing hosts that I have in `~/.ssh/config`. My `fabfile.py` is as follows: ``` from fabric.api import run, env env.hosts = ['lulu'] def whoami(): run('whoami') ``` Running `$ fab whoami` gives: > [lulu] run: w...
Note that this also happens when the name is not in `/etc/hosts`. I had the same problem and had to add the host name to both that file and `~/.ssh/config`.
Connecting to a host listed in ~/.ssh/config when using Fabric
3,077,281
71
2010-06-19T21:21:23Z
9,685,171
114
2012-03-13T13:42:03Z
[ "python", "ssh", "fabric" ]
I'm having trouble with [`Fabric`](http://docs.fabfile.org/0.9.1/api/contrib/project.html) not recognizing hosts that I have in `~/.ssh/config`. My `fabfile.py` is as follows: ``` from fabric.api import run, env env.hosts = ['lulu'] def whoami(): run('whoami') ``` Running `$ fab whoami` gives: > [lulu] run: w...
Since version 1.4.0, [Fabric uses your ssh config](http://docs.fabfile.org/en/1.4.0/usage/execution.html#ssh-config) (partly). However, you need to explicitly enable it, with ``` env.use_ssh_config = True ``` somewhere near the top of your fabfile. Once you do this, Fabric should read your ssh config (from `~/.ssh/co...
batch renaming 100K files with python
3,077,794
9
2010-06-20T00:48:18Z
3,077,839
8
2010-06-20T01:03:07Z
[ "python", "file-rename", "batch-rename" ]
I have a folder with over 100,000 files, all numbered with the same stub, but without leading zeros, and the numbers aren't always contiguous (usually they are, but there are gaps) e.g: ``` file-21.png, file-22.png, file-640.png, file-641.png, file-642.png, file-645.png, file-2130.png, file-2131.png, file-301...
``` import re thenum = re.compile('^file-(\d+)\.png$') def bynumber(fn): mo = thenum.match(fn) if mo: return int(mo.group(1)) allnames = os.listdir('.') allnames.sort(key=bynumber) ``` Now you have the files in the order you want them and can loop ``` for i, fn in enumerate(allnames): ... ``` using the progr...
How does the right-shift operator work in a python print statement?
3,078,042
11
2010-06-20T02:47:31Z
3,078,060
10
2010-06-20T02:56:08Z
[ "python", "grammar" ]
I've seen someone using "print" with ">>" to write stuffs into a file: ``` In [7]: with open('text', 'w') as f: ...: print >> f, "Hello, world!" ...: In [8]: !type text Hello, world! ``` How does it work? When should I use this instead of just using the "write" method?
From [https://docs.python.org/2/reference/simple\_stmts.html#the-print-statement](http://docs.python.org/reference/simple_stmts.html#print) > print also has an extended form, > defined by the second portion of the > syntax described above. This form is > sometimes referred to as “print > chevron.” In this form, th...
Adding printf to the starting of all functions in a file
3,078,680
7
2010-06-20T08:47:06Z
3,078,693
23
2010-06-20T08:54:39Z
[ "python", "c", "perl" ]
I have some very large C files, having lots of functions. I need to trace the execution path at run time. There is no way I can trace it through debugging as its a hypervisor code currently running over qemu and doing a lot of binary translations. Can anyone point me to some script in Perl or Python which can add a `p...
Just pass `-finstrument-functions` to gcc when compiling. See the `gcc(1)` man page for details.
Forcing scons to use older compiler?
3,079,344
9
2010-06-20T13:16:07Z
3,083,882
17
2010-06-21T10:33:26Z
[ "python", "scons" ]
I have a C++ project which is using boost. The whole project is built using scons + Visual Studio 2008. We've installed Visual Studio 2010 and it turned out scons was attempting to use the later compiler instead of the old one - and failed to build the project as boost and visual studio 2010 don't like each other very ...
You can modify the scons Environment() by just choosing the version you want: env = Environment(MSVC\_VERSION=`<someversion>`) From the scons manpage: > MSVC\_VERSION Sets the preferred > version of Microsoft Visual C/C++ to > use. > > If $MSVC\_VERSION is not set, SCons > will (by default) select the latest > versi...
Ruby HAML with Django?
3,079,368
19
2010-06-20T13:24:12Z
3,129,231
8
2010-06-27T23:06:56Z
[ "python", "ruby", "django", "haml" ]
Ok, so I really love HAML. Particularly, I love the integration with RedCloth and BlueCloth, so I can use Markdown and Textile intermixed with my HAML. I also love Python and Django. So, I would like to use HAML with Django. Now, I already understand that there are some attempts at cloning HAML-like syntax in Python ...
**Question 1**: static HTML files should work finely (unless you plan to use HAML's ruby evaluation feature to dynamically content). I use a similar way on a php website with SASS stylesheets. Just make sure you start HAML in directory watch mode before starting to hack ;) **Question 2**: while forking a ruby process ...
Can I use Ruby and Python together?
3,079,531
8
2010-06-20T14:15:15Z
3,079,547
8
2010-06-20T14:21:40Z
[ "python", "ruby" ]
Is there something like JRuby but for Ruby and Python? Not that it would actually be useful to me, but just wondering.
If you develop for the .NET Framework Version 4.0, you can write code in IronRuby that calls methods that were written in IronPython and vice versa.
Non-sequential substitution in SymPy
3,080,450
10
2010-06-20T18:33:38Z
10,963,602
10
2012-06-09T18:41:46Z
[ "python", "math", "substitution", "symbolic-math", "sympy" ]
I'm trying to use [SymPy][1] to substitute multiple terms in an expression at the same time. I tried the [subs function][2] with a dictionary as parameter, but found out that it substitutes sequentially. ``` In : a.subs({a:b, b:c}) Out: c ``` The problem is the first substitution resulted in a term that can be substi...
The current version of sympy provides the keyword simultaneous. The complicated operations in the previous answers are no more necessary: ``` In [1]: (x*sin(y)).subs([(x,y),(y,x)],simultaneous=True) Out[1]: y⋅sin(x) ```
How to exit when viewing python help like help(os.listdir)
3,080,563
20
2010-06-20T19:05:15Z
3,080,574
46
2010-06-20T19:08:38Z
[ "python" ]
when the help window pops up, what are the basic commands (mac os) to page up/down, end of document and **exiting** the help screen? I just had to close my terminal as I couldn't figure it out!
You are probably in [`less`](http://www.gnu.org/software/less/) (this is configurable through the `PAGER` environment variable, but you probably haven't changed that). Press `h` for help and `q` to quit.
Change Unix password from command line over Python/Fabric
3,080,585
7
2010-06-20T19:11:10Z
3,080,651
13
2010-06-20T19:30:06Z
[ "python", "unix", "passwords", "fabric", "passwd" ]
I would like a way to update my password on a remote `Ubuntu 10.4` box with [fabric](http://docs.fabfile.org/0.9.1/index.html). I would expect my `fabfile.py` would look something like this: ``` def update_password(old_pw, new_pw): # Connects over ssh with a public key authentication run("some_passwd_cmd --ol...
You could feed the new and old passwords into `passwd` using `echo` e.g. ``` echo -e "oldpass\\nnewpass\\nnewpass" | passwd ``` (the `-e` option for `echo` enables interpretation of backslash escapes so the newlines are interpreted as such)
Change Unix password from command line over Python/Fabric
3,080,585
7
2010-06-20T19:11:10Z
5,137,688
10
2011-02-28T02:29:27Z
[ "python", "unix", "passwords", "fabric", "passwd" ]
I would like a way to update my password on a remote `Ubuntu 10.4` box with [fabric](http://docs.fabfile.org/0.9.1/index.html). I would expect my `fabfile.py` would look something like this: ``` def update_password(old_pw, new_pw): # Connects over ssh with a public key authentication run("some_passwd_cmd --ol...
The trick is to use a combination of `usermod` and Python’s `crypt` to change your password: ``` from crypt import crypt from getpass import getpass from fabric.api import * def change_password(user): password = getpass('Enter a new password for user %s:' % user) crypted_password = crypt(password, 'salt') ...
Why can't I use ttk in Python?
3,080,918
8
2010-06-20T20:58:22Z
3,081,089
9
2010-06-20T21:56:33Z
[ "python", "python-3.x", "tkinter" ]
When I type `from Tkinter import ttk` it says that there is no module named `ttk`, and also on many websites online the `t` in `tkinter` is always *lowercase*, but when I type `tkinter` in Python it throws an error. Why is that?
`Tkinter` in python 2.6 is capitalized, in python 3 it is lowercase, `tkinter`
Reconstituting Strings in Python
3,081,184
2
2010-06-20T22:29:19Z
3,081,218
7
2010-06-20T22:42:40Z
[ "python" ]
I would like to do something like: ``` temp=a.split() #do some stuff with this new list b=" ".join(temp) ``` where a is the original string, and b is after it has been modified. The problem is that when performing such methods, the newlines are removed from the new string. So how can I do this without removing newlin...
I assume in your third line you mean `join(temp)`, not `join(a)`. To split and yet keep the exact "splitters", you need the [re.split](http://docs.python.org/library/re.html?highlight=re.split#re.split) function (or `split` method of RE objects) with a capturing group: ``` >>> import re >>> f='tanto va\nla gatta al l...
Python Module Initialization Order?
3,082,015
9
2010-06-21T03:49:17Z
3,082,097
12
2010-06-21T04:21:56Z
[ "python", "initialization", "order" ]
I am a Python newbie coming from a C++ background. While I know it's not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is still a general question to ask: Under C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inab...
Python import executes new Python modules from beginning to end. Subsequent imports only result in a copy of the existing reference in `sys.modules`, even if still in the middle of importing the module due to a circular import. Module attributes ("global variables" are actually at the module scope) that have been initi...
Python Module Initialization Order?
3,082,015
9
2010-06-21T03:49:17Z
3,082,252
8
2010-06-21T05:14:47Z
[ "python", "initialization", "order" ]
I am a Python newbie coming from a C++ background. While I know it's not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is still a general question to ask: Under C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inab...
> Under C++, there is a well known problem called global/static variable initialization order fiasco, due to C++'s inability to decide which global/static variable would be initialized first across compilation units, I think that statement highlights a key difference between Python and C++: in Python, there is no such...
How to pull a BitBucket repository without access to hg
3,082,107
3
2010-06-21T04:25:02Z
3,082,144
9
2010-06-21T04:37:06Z
[ "python", "mercurial", "bitbucket" ]
I was wondering if it was possible to pull a private mercurial repo to a server without access to hg. I have SSH access, but do not have the ability to install HG. I was thinking some kind of Python script that used http access or something, but I wasn't sure. I was also thinking this might only be possible with public...
What good would getting the repository be if you don't have mercurial installed and can't install it? Do you instead mean get the files in a specific revision? If so you can easily do that using: ``` wget https://username:password@bitbucket.org/user/repo/get/REVISIONHASH.zip ``` I'm pretty sure you can put user/pass...
What's a good document standard to use programmatically?
3,082,502
3
2010-06-21T06:25:11Z
3,082,512
9
2010-06-21T06:27:27Z
[ "python", "pyqt", "document" ]
I'm writing a program that requires input in the form of a document, it needs to replace a few values, insert a table, and convert it to PDF. It's written in Python + Qt (PyQt). Is there any well known document standard which can be easily used programmatically? It must be cross platform, and preferably open. 1. I hav...
Have you looked into using LaTeX documents? They are perfect to use programatically (*compiling* documents? You gotta love that...), and you have several Python frameworks you can use such as [plasTeX](http://plastex.sourceforge.net/plastex/index.html) and [PyTex](http://www.pytex.org/). Exporting a LaTeX documents t...
Generating Python soaplib stubs from WSDL
3,083,186
9
2010-06-21T08:49:30Z
3,086,597
9
2010-06-21T16:45:30Z
[ "python", "soap" ]
I'd like to generate a stub SOAP web service class using the Python soaplib module, based on an existing WSDL. The idea is to generate a mock for a third party web service. Does any such code generator exist, or must we write our own? Martin
Okay, I had a go at hacking my wsdl2interface (http://pypi.python.org/pypi/wsdl2interface) script to output soaplib code. I think I have something that works, though it's not pretty or especially well tested. I'll paste it here for the record. I could be persuaded to release it if someone needs it, though it's not exa...
chat app. for django
3,083,309
5
2010-06-21T09:09:46Z
3,084,328
9
2010-06-21T11:45:23Z
[ "python", "django", "chat", "django-views", "livechat" ]
Is there any facebook like chat application to integrate to django.If so please give an example and the source link Thanks..
Here are three: * <http://code.google.com/p/django-chat/> - demo works well, but code last updated in 2008, so possibly unmaintained * <http://code.google.com/p/django-jchat/> - uses jQuery. Maintained code with [good blog posts](http://pythonhaven.wordpress.com/2009/07/13/django-powered-ajax-chat-%E2%80%93-part-2/) e...
Facebook Python-SDK VS. PyFacebook?
3,084,230
9
2010-06-21T11:29:39Z
3,084,294
11
2010-06-21T11:39:53Z
[ "python", "facebook", "pyfacebook" ]
I'm starting to develop a facebook application using Django. I'm trying to choose the appropriate API wrapper for my application and I can't decide whether to use PyFacebook (very well documented but no official release) or the official Facebook Python SDK (which is surprisingly poorly documented). Are there any majo...
I believe [PyFacebook](http://github.com/sciyoshi/pyfacebook/) was made for the old Facebook API (used to be the way to go) while the [Facebook Platform Python SDK](http://github.com/facebook/python-sdk/) is a new official library from facebook and is aimed towards the new [Graph API](http://developers.facebook.com/doc...
python string substitution
3,084,637
9
2010-06-21T12:35:15Z
3,084,660
10
2010-06-21T12:37:40Z
[ "python" ]
Is there a simple way of passing a list as the parameter to a string substitution in python ? Something like: `w = ['a', 'b', 'c']` `s = '%s\t%s\t%s\n' % w` Something similar to the way dictionaries work in this case.
Just convert the list to a tuple: ``` w = ['a', 'b', 'c'] s = '%s\t%s\t%s\n' % tuple(w) ```
Pros and cons for different configuration formats?
3,085,029
17
2010-06-21T13:26:22Z
3,086,617
9
2010-06-21T16:48:55Z
[ "python", "xml", "json", "configuration-files" ]
I've seen people using \*.cfg (Python Buildout), \*.xml (Gnome), \*.json (Chrome extension), \*.yaml (Google App Engine), \*.ini and even \*.py for app configuration files (like Django). My question is: why there are so many different configuration file formats? I can see an advantage from a xml vs json approach (much...
It's mostly personal preference, purpose, and available libraries. Personally I think xml is way too verbose for config files, but it is popular and has great libraries. .cfg, .ini are legacy formats that work well and many languages have an included library that reads them. I've used it in Java, Python, C++ without i...
Create an utf-8 csv file in Python
3,085,263
16
2010-06-21T13:58:24Z
3,085,443
14
2010-06-21T14:19:54Z
[ "python", "encoding", "utf-8", "csv" ]
I can't create an utf-8 csv file in Python. I'm trying to read it's docs, and in the [examples section](http://docs.python.org/library/csv.html#csv-examples), it says: > For all other encodings the following > UnicodeReader and UnicodeWriter > classes can be used. They take an > additional encoding parameter in their...
You don't have to use `codecs.open`; `UnicodeWriter` takes Unicode input and takes care of encoding everything into UTF-8. When `UnicodeWriter` writes into the file handle you passed to it, everything is already in UTF-8 encoding (therefore it works with a normal file you opened with `open`). By using `codecs.open`, y...
python How can I strip first and last double quotes
3,085,382
42
2010-06-21T14:13:44Z
3,085,402
75
2010-06-21T14:15:56Z
[ "python", "string", "strip" ]
I want to strip double quotes from ``` string = '"" " " ""\\1" " "" ""' ``` to become ``` string = '" " " ""\\1" " "" "' ``` I tried to use `rstrip`, `lstrip` and `strip('[^\"]|[\"$]')` but it did not work. How can I do this? Thank you for helping me.
If the quotes you want to strip are always going to be "first and last" as you said, then you could simply use: `string = string[1:-1]`
python How can I strip first and last double quotes
3,085,382
42
2010-06-21T14:13:44Z
3,085,406
7
2010-06-21T14:16:26Z
[ "python", "string", "strip" ]
I want to strip double quotes from ``` string = '"" " " ""\\1" " "" ""' ``` to become ``` string = '" " " ""\\1" " "" "' ``` I tried to use `rstrip`, `lstrip` and `strip('[^\"]|[\"$]')` but it did not work. How can I do this? Thank you for helping me.
If string is always as you show: ``` string[1:-1] ```
python How can I strip first and last double quotes
3,085,382
42
2010-06-21T14:13:44Z
3,085,942
45
2010-06-21T15:20:58Z
[ "python", "string", "strip" ]
I want to strip double quotes from ``` string = '"" " " ""\\1" " "" ""' ``` to become ``` string = '" " " ""\\1" " "" "' ``` I tried to use `rstrip`, `lstrip` and `strip('[^\"]|[\"$]')` but it did not work. How can I do this? Thank you for helping me.
If you can't assume that all the strings you process have double quotes you can use something like this: ``` if string.startswith('"') and string.endswith('"'): string = string[1:-1] ``` **Edit:** I'm sure that you just used `string` as the variable name for exemplification here and in your real code it has a us...
python How can I strip first and last double quotes
3,085,382
42
2010-06-21T14:13:44Z
3,086,018
28
2010-06-21T15:31:49Z
[ "python", "string", "strip" ]
I want to strip double quotes from ``` string = '"" " " ""\\1" " "" ""' ``` to become ``` string = '" " " ""\\1" " "" "' ``` I tried to use `rstrip`, `lstrip` and `strip('[^\"]|[\"$]')` but it did not work. How can I do this? Thank you for helping me.
To remove the first and last characters, and in each case do the removal only if the character in question is a double quote: ``` import re s = re.sub(r'^"|"$', '', s) ``` Note that the RE pattern is different than the one you had given, and the operation is `sub` ("substitute") with an empty replacement string (`st...
python How can I strip first and last double quotes
3,085,382
42
2010-06-21T14:13:44Z
3,086,161
7
2010-06-21T15:52:12Z
[ "python", "string", "strip" ]
I want to strip double quotes from ``` string = '"" " " ""\\1" " "" ""' ``` to become ``` string = '" " " ""\\1" " "" "' ``` I tried to use `rstrip`, `lstrip` and `strip('[^\"]|[\"$]')` but it did not work. How can I do this? Thank you for helping me.
Almost done. Quoting from <http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip> > The chars argument is a string > specifying the set of characters to be > removed. [...] > The chars argument is not a prefix or > suffix; rather, all combinations of > its values are stripped: So the argument is no...
python How can I strip first and last double quotes
3,085,382
42
2010-06-21T14:13:44Z
20,577,580
22
2013-12-13T23:12:46Z
[ "python", "string", "strip" ]
I want to strip double quotes from ``` string = '"" " " ""\\1" " "" ""' ``` to become ``` string = '" " " ""\\1" " "" "' ``` I tried to use `rstrip`, `lstrip` and `strip('[^\"]|[\"$]')` but it did not work. How can I do this? Thank you for helping me.
**IMPORTANT:** I'm extending the question/answer to strip either single or double quotes. And I interpret the question to mean that BOTH quotes must be present, and matching, to perform the strip. Otherwise, the string is returned unchanged. To "dequote" a string representation, that might have either single or double...
Adding a scrollbar to a group of widgets in Tkinter
3,085,696
24
2010-06-21T14:50:14Z
3,092,341
50
2010-06-22T10:49:17Z
[ "python", "tkinter" ]
I am using Python to parse entries from a log file, and display the entry contents using Tkinter and so far it's been excellent. The output is a grid of label widgets, but sometimes there are more rows than can be displayed on the screen. I'd like to add a scrollbar, which looks like it should be very easy, but I can't...
## Overview Create a canvas widget and associate the scrollbars with that widget. Then, into that canvas embed the frame that contains your label widgets. Determine the width/height of the frame and feed that into the canvas `scrollregion` option so that the scrollregion exactly matches the size of the frame. Drawing...
Debug Jinja2 in Google App Engine
3,086,091
27
2010-06-21T15:43:41Z
3,694,434
29
2010-09-12T10:02:47Z
[ "python", "debugging", "google-app-engine", "jinja2" ]
When I'm running Jinja2 in Google App Engine, I get useless debugging information. I gather this is because of this item in the FAQ: > ## [My tracebacks look weird. What’s happening?](http://jinja.pocoo.org/2/documentation/faq#my-tracebacks-look-weird-what-s-happening) > > If the speedups module is not compiled and ...
You can get around this by adding \_ctypes and gestalt to the development server's C module whitelist with monkeypatching. To do so, put the following snippet at the top of your main.py: ``` import os if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'): # Enable ctypes for Jinja debugging from google.a...
Confused, are languages like python, ruby single threaded? unlike say java? (for web apps)
3,086,467
10
2010-06-21T16:29:18Z
3,086,582
12
2010-06-21T16:43:28Z
[ "java", "python", "ruby", "multithreading" ]
I was reading how Clojure is 'cool' because of its syntax + it runs on the JVM so it is multithreaded etc. etc. Are languages like ruby and python single threaded in nature then? (when running as a web app). What are the underlying differences between python/ruby and say java running on tomcat? Doesn't the web serve...
Both Python and Ruby have full support for multi-threading. There are some implementations (e.g. CPython, MRI, YARV) which cannot actually run threads in parallel, but that's a limitation of those specific implementations, not the language. This is similar to Java, where there are also some implementations which cannot...
Python memory usage: Which of my objects is hogging the most memory?
3,086,514
4
2010-06-21T16:34:29Z
3,086,573
7
2010-06-21T16:42:52Z
[ "python", "memory-management" ]
The program I've written stores a large amount of data in dictionaries. Specifically, I'm creating 1588 instances of a class, each of which contains 15 dictionaries with 1500 float to float mappings. This process has been using up the 2GB of memory on my laptop pretty quickly (I start writing to swap at about the 1000t...
The floats do take up 16 bytes apiece, and a dict with 1500 entries about 100k: ``` >> sys.getsizeof(1.0) 16 >>> d = dict.fromkeys((float(i) for i in range(1500)), 2.0) >>> sys.getsizeof(d) 98444 ``` so the 22,500 dicts take over 2GB all by themselves, the 68 million floats another GB or so. Not sure how you compute ...
Python Exceptions: EAFP and What is Really Exceptional?
3,086,806
15
2010-06-21T17:13:49Z
3,087,143
26
2010-06-21T18:00:28Z
[ "python", "exception" ]
It's been said in a couple places ([here](http://stackoverflow.com/questions/1835756/using-try-vs-if-in-python) and [here](http://stackoverflow.com/questions/2739582/condition-checking-vs-exception-handling)) that Python's emphasis on "it's easier to ask for forgiveness than permission" (EAFP) should be tempered with t...
> exceptions should only be called in > truly exceptional cases Not in Python: for example, **every** `for` loop (unless it prematurely `break`s or `return`s) terminates by an exception (`StopIteration`) being thrown and caught. So, an exception that happens once per loop is hardly strange to Python -- it's there more...
Python Exceptions: EAFP and What is Really Exceptional?
3,086,806
15
2010-06-21T17:13:49Z
3,088,737
8
2010-06-21T21:49:26Z
[ "python", "exception" ]
It's been said in a couple places ([here](http://stackoverflow.com/questions/1835756/using-try-vs-if-in-python) and [here](http://stackoverflow.com/questions/2739582/condition-checking-vs-exception-handling)) that Python's emphasis on "it's easier to ask for forgiveness than permission" (EAFP) should be tempered with t...
Throwing exceptions is expensive in most low-level languages like C++. That influences a lot of the "common wisdom" about exceptions, and doesn't apply so much to languages that run in a VM, like Python. There's not such a major cost in Python for using an exception instead of a conditional. (This is a case where the ...
How do I convert this list of dictionaries to a csv file? [Python]
3,086,973
42
2010-06-21T17:36:13Z
3,087,011
87
2010-06-21T17:41:08Z
[ "python", "csv", "dictionary" ]
I have a list of dictionaries that looks something like this: ``` toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}] ``` What should I do to convert this to a csv file that looks something like this: ``` name,age,weight bob,25,200 jim,31,180 ```
``` import csv toCSV = [{'name':'bob','age':25,'weight':200}, {'name':'jim','age':31,'weight':180}] keys = toCSV[0].keys() with open('people.csv', 'wb') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(toCSV) ``` EDIT: My prior solutio...
How do I convert this list of dictionaries to a csv file? [Python]
3,086,973
42
2010-06-21T17:36:13Z
3,087,014
14
2010-06-21T17:41:24Z
[ "python", "csv", "dictionary" ]
I have a list of dictionaries that looks something like this: ``` toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}] ``` What should I do to convert this to a csv file that looks something like this: ``` name,age,weight bob,25,200 jim,31,180 ```
In Python's csv module there is a [DictWriter](http://docs.python.org/library/csv.html#csv.DictWriter) which will probably be helpful.
what does python.exe take as arguments?
3,088,493
3
2010-06-21T21:01:21Z
3,088,660
8
2010-06-21T21:34:14Z
[ "python", "arguments" ]
does it take the filename of the .py and then what?
Documentation [here.](http://docs.python.org/using/cmdline.html)
testing command line utilities
3,088,556
11
2010-06-21T21:12:09Z
3,090,460
13
2010-06-22T05:16:40Z
[ "python", "language-agnostic", "bash", "testing", "command-line" ]
I'm looking for a way to run tests on command-line utilities written in bash, or any other language. I'd like to find a testing framework that would have statements like ``` setup: command = 'do_awesome_thing' filename = 'testfile' args = ['--with', 'extra_win', '--file', filename] run_command command...
Check out [ScriptTest](http://pythonpaste.org/scripttest/) : ``` from scripttest import TestFileEnvironment env = TestFileEnvironment('./scratch') def test_script(): env.reset() result = env.run('do_awesome_thing testfile --with extra_win --file %s' % filename) # or use a list like ['do_awesome_thing', '...
Python: Not all of arguments converted during string formatting
3,089,038
13
2010-06-21T22:47:54Z
3,089,044
28
2010-06-21T22:49:41Z
[ "python", "string", "datetime", "formatting" ]
Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below: ``` from subprocess import Popen import datetime today = datetime.date.today() today...
You're putting the string formatting in the wrong place; it needs to be right after the string that's being formatted: ``` f = open("%s.sql" % (today), "w") ``` It's legal to not pass any formatting arguments, like you did with `"%s.sql"`, but it's not legal to pass arguments but not the right amount (`"w" % (today)`...
How do I get the ID of an object after persisting it in PyMongo?
3,089,067
4
2010-06-21T22:55:42Z
3,089,373
12
2010-06-22T00:21:23Z
[ "python", "mongodb", "pymongo" ]
I have a PyMongo newbie question: If `collection` is a PyMongo [Collection](http://api.mongodb.org/python/1.7%2B/api/pymongo/collection.html) and I use it to save an object with ``` obj = {'foo': 'bar'} collection.insert(obj) ``` then MongoDB automatically generates an `_id` field for `obj`; once can confirm this wit...
You just need to pass `remove` a dict, just like you did `insert`. So, to remove a document based on its `_id` value, do something like: ``` collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')}) ```
Pydev in Eclipse default working directory
3,089,070
4
2010-06-21T22:56:37Z
3,089,474
8
2010-06-22T00:47:35Z
[ "python", "eclipse" ]
What is the default working directory for my project? I have several projects under my workspace, and a couple of run configurations. I use os.getcwd() and the directory goes to other project's folder, after deleting all run configurations, the directory goes to eclipse's install folder. How to make the default working...
Open Run Dialog...-> Select your run configuration->Arguments Tab->Working directory: mine is set to ${workspace\_loc}:test/src/ for a project name test i created in my workspace
Python getattr equivalent for dictionaries?
3,089,186
30
2010-06-21T23:28:45Z
3,089,192
49
2010-06-21T23:29:58Z
[ "python" ]
What's the most succinct way of saying, in Python, "Give me `dict['foo']` if it exists, and if not, give me this other value `bar`"? If I were using an object rather than a dictionary, I'd use `getattr`: ``` getattr(obj, 'foo', bar) ``` but this raises a key error if I try using a dictionary instead (a distinction I ...
`dict.get(key, default)` returns `dict[key]` if key in dict, else returns default. Note that the default for `default` is `None` so if you say `dict.get(key)` and key is not in dict then this will just return `None` rather than raising a `KeyError` as happens when you use the `[]` key access notation.
What language is this program written in?
3,089,531
15
2010-06-22T01:04:17Z
3,089,542
18
2010-06-22T01:06:44Z
[ "python", "ruby-on-rails", "c", "ruby", "language-identification" ]
This looks like code in the C language, but I am not completely sure ... ``` # define v putchar # define print(x) main(){v(4+v(v(52)-4));return 0;}/* #>+++++++4+[>++++++<-]>++++.----.++++.*/ print(202*2);exit(); #define/*>.@*/exit() ```
it is a little polyglot for Befunge-93, Brainf\*ck, Python, Ruby, Perl, and C that simply prints 404 to stdout. <http://meta.stackexchange.com/questions/27112/amusing-404-page-not-found-images-for-trilogy-sites>
What language is this program written in?
3,089,531
15
2010-06-22T01:04:17Z
3,221,310
14
2010-07-11T00:02:18Z
[ "python", "ruby-on-rails", "c", "ruby", "language-identification" ]
This looks like code in the C language, but I am not completely sure ... ``` # define v putchar # define print(x) main(){v(4+v(v(52)-4));return 0;}/* #>+++++++4+[>++++++<-]>++++.----.++++.*/ print(202*2);exit(); #define/*>.@*/exit() ```
As the original author of the polyglot, and the author of the accepted answer in the meta post, I feel I have the right -- nay, the *duty* -- to re-post the explanation here: --- The easy versions are Python, Perl, and Ruby: the only code executed is ``` print(202*2);exit(); ``` because they all treat `#` as a line...
Is there a python equivalent to the Unix `which` command?
3,089,939
5
2010-06-22T02:50:24Z
3,089,951
7
2010-06-22T02:54:04Z
[ "python" ]
I'd like to know where the module I'm about to import is coming from. Is there a `which` command in python? Example: ``` >>> which module_name /usr/lib/python2.6/site-packages/module_name.py ```
``` import imp imp.find_module(module_name) ``` > Help on built-in function find\_module > in module imp: > > find\_module(...) > find\_module(name, [path]) -> (file, filename, (suffix, mode, type)) > Search for a module. If path is omitted or None, search for a > built-in, frozen or special module and continue ...
Python - Find the greatest number in a set of numbers
3,090,175
37
2010-06-22T03:58:10Z
3,090,183
57
2010-06-22T03:59:45Z
[ "python", "numbers" ]
Is there is any easy way or function to determine the greatest number in a python list? I could just code it, as I only have three numbers, however it would make the code a lot less redundant if I could tell the greatest with a built in function or something.
What about max() ``` foo = [1,2,3] print max(foo) ```
Python - Find the greatest number in a set of numbers
3,090,175
37
2010-06-22T03:58:10Z
3,090,191
8
2010-06-22T04:01:18Z
[ "python", "numbers" ]
Is there is any easy way or function to determine the greatest number in a python list? I could just code it, as I only have three numbers, however it would make the code a lot less redundant if I could tell the greatest with a built in function or something.
You can use the inbuilt function [`max()`](http://docs.python.org/library/functions.html) with multiple arguments: ``` print max(1, 2, 3) ``` or a list: ``` list = [1, 2, 3] print max(list) ``` or in fact anything iterable.
In Django, how do I objects.get, but return None when nothing is found?
3,090,302
65
2010-06-22T04:38:42Z
3,090,342
104
2010-06-22T04:47:09Z
[ "python", "mysql", "database", "django" ]
``` go = Content.objects.get(name="baby") # go should be None, since nothing is in the database. ```
There is no 'built in' way to do this. Django will raise the DoesNotExist exception every time. The idiomatic way to handle this in python is to wrap it in a try catch: ``` try: x = SomeModel.objects.get(foo='bar') except SomeModel.DoesNotExist: x = None ``` What I did do, is to sublcass models.Manager, create ...
In Django, how do I objects.get, but return None when nothing is found?
3,090,302
65
2010-06-22T04:38:42Z
3,090,348
16
2010-06-22T04:48:16Z
[ "python", "mysql", "database", "django" ]
``` go = Content.objects.get(name="baby") # go should be None, since nothing is in the database. ```
[From django docs](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id5) > `get()` raises a `DoesNotExist` exception if an object is not found for the given parameters. This exception is also an attribute of the model class. The `DoesNotExist` exception inherits from `django.core.exceptions.ObjectDoesNotExis...
In Django, how do I objects.get, but return None when nothing is found?
3,090,302
65
2010-06-22T04:38:42Z
20,674,112
12
2013-12-19T05:31:08Z
[ "python", "mysql", "database", "django" ]
``` go = Content.objects.get(name="baby") # go should be None, since nothing is in the database. ```
You can create a generic function for this. ``` def get_or_none(classmodel, **kwargs): try: return classmodel.objects.get(**kwargs) except classmodel.DoesNotExist: return None ``` Use this like below: ``` go = get_or_none(Content,name="baby") ``` go will be None if no entry matches else will...
In Django, how do I objects.get, but return None when nothing is found?
3,090,302
65
2010-06-22T04:38:42Z
24,916,312
7
2014-07-23T16:44:44Z
[ "python", "mysql", "database", "django" ]
``` go = Content.objects.get(name="baby") # go should be None, since nothing is in the database. ```
you could use `exists` with a filter: ``` Content.objects.filter(name="baby").exists() #returns False or True depending on if there is anything in the QS ``` just an alternative for if you only want to know if it exists
In Django, how do I objects.get, but return None when nothing is found?
3,090,302
65
2010-06-22T04:38:42Z
29,455,777
31
2015-04-05T09:09:35Z
[ "python", "mysql", "database", "django" ]
``` go = Content.objects.get(name="baby") # go should be None, since nothing is in the database. ```
Since django 1.6 you can use [first()](https://docs.djangoproject.com/en/1.7/ref/models/querysets/#first) method like so: ``` Content.objects.filter(name="baby").first() ```
Copy files to network path or drive using python on OSX
3,090,724
3
2010-06-22T06:20:54Z
3,091,702
10
2010-06-22T09:07:34Z
[ "python", "osx", "network-programming", "smb" ]
I have a similar question like the one asked here but I need it to work on OSX. <http://stackoverflow.com/questions/2625877/copy-files-to-nework-path-or-drive-using-python> So i want to save a file on a SMB network share. Can this be done? Thanks!
Yes, it can be done. First, mount your SMB network share to the local filesystem by calling a command like this from Python: ``` mount -t smbfs //user@server/sharename share ``` (You can do it using the `subprocess` module). `share` is the name of the directory where the SMB network share will be mounted to, and I gu...
+\ operator in Python
3,090,780
3
2010-06-22T06:31:05Z
3,090,796
7
2010-06-22T06:32:58Z
[ "python", "string", "operators" ]
What does the +\ operator do in Python? I came across this piece of code - ``` rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\ 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\ '&ignore=.csv').readlines( ) ``` and can't find any references that explain it.
It's not an operator, it's just the + operator followed by the line continuation \
+\ operator in Python
3,090,780
3
2010-06-22T06:31:05Z
3,090,798
18
2010-06-22T06:33:12Z
[ "python", "string", "operators" ]
What does the +\ operator do in Python? I came across this piece of code - ``` rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\ 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\ '&ignore=.csv').readlines( ) ``` and can't find any references that explain it.
The `+` is addition. The `\` at the end of the line continues the current statement or expression on the next line.
+\ operator in Python
3,090,780
3
2010-06-22T06:31:05Z
3,090,879
11
2010-06-22T06:51:32Z
[ "python", "string", "operators" ]
What does the +\ operator do in Python? I came across this piece of code - ``` rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\ 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\ '&ignore=.csv').readlines( ) ``` and can't find any references that explain it.
N.B. The `\` continuation is unnecessary in this case since the expression is inside parentheses. Python is smart enough to know that a line continues until all brackets, braces and parentheses are balanced. Unnecessary continuation characters are a minor bugbear of mine, and I delete them at every opportunity. They c...
'Put' in SFTP using PAramiko
3,091,326
15
2010-06-22T08:09:34Z
3,099,255
29
2010-06-23T06:01:37Z
[ "python", "sftp", "paramiko" ]
I've installed and written the following Paramiko which is unable to put the file. It is easily able to 'get' a file and execute 'ls' commands on it. ``` #set username & password username='runaway' password='runaway' port=22 source= '/Unzip.sh' destination ='/var/mpx/www/http' #SFTP client.load_system_host_keys() p...
The solution seemed very funny to me! ``` source= '/Unzip.sh' destination ='/var/mpx/www/http/Unzip.sh' ``` Just modified the destination path to include the file name as well. Didn't expect some error like this coming from a Python package.
Python time.gmtime() returning time that's 5 hours ahead of system time
3,092,479
4
2010-06-22T11:07:07Z
3,092,521
19
2010-06-22T11:14:01Z
[ "python", "time", "timezone" ]
I have been scouring the google machine and have come up with nothing to answer this. When making calls to: ``` time.gmtime() ``` This ends up returning a time, as the subject line says, 5 hours ahead of my system time. I cannot figure out what is going on. time.tzname() returns the proper timezone. Aside from settin...
Have you tried moving to London? I think that will solve your problem. :)
How can I check if a Python unicode string contains non-Western letters?
3,094,498
16
2010-06-22T15:13:35Z
3,308,844
20
2010-07-22T12:33:14Z
[ "python", "django", "unicode" ]
I have a Python Unicode string. I want to make sure it only contains letters from the Roman alphabet (A through Z), as well as letters commonly found in European alphabets, such as ß, ü, ø, é, à, and î. It should *not* contain characters from other alphabets (Chinese, Japanese, Korean, Arabic, Cyrillic, Hebrew, e...
``` import unicodedata as ud latin_letters= {} def is_latin(uchr): try: return latin_letters[uchr] except KeyError: return latin_letters.setdefault(uchr, 'LATIN' in ud.name(uchr)) def only_roman_chars(unistr): return all(is_latin(uchr) for uchr in unistr if uchr.isalpha()) ...
Is there a Java equivalent of Python's dictionary display?
3,094,635
3
2010-06-22T15:31:58Z
3,094,668
7
2010-06-22T15:34:58Z
[ "java", "python", "dictionary" ]
In Python I'm using a dictionary display: ``` myAnonDict = {'foo': 23, 'bar': 'helloworld'} ``` Is there an equivalent in Java? [edited 'anonymous dictionary' to read 'dictionary display']
``` Map<String, String> myMap = new HashMap<String, String>(); myMap.put("foo", "23"); myMap.put("bar", "helloworld"); ``` This is different from yours because yours has heterogeneous data types whereas mine deals in Strings only. You can actually have mixed collections in Java, too, but I hate doing that. Kind of def...
Editing elements in a list in python
3,094,659
8
2010-06-22T15:34:12Z
3,094,688
14
2010-06-22T15:37:05Z
[ "python", "regex", "string" ]
How do I remove a character from an element in a list? Example: ``` mylist = ['12:01', '12:02'] ``` I want to remove the colon from the time stamps in a file, so I can more easily convert them to a 24hour time. Right now I am trying to loop over the elements in the list and search for the one's containing a colon an...
Use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) to generate a new list: ``` >>> mylist = ['12:01', '12:02'] >>> mylist = [s.replace(':', '') for s in mylist] >>> print mylist ['1201', '1202'] ``` The reason that your solution doesn't work is that `re.sub` returns a ...
Editing elements in a list in python
3,094,659
8
2010-06-22T15:34:12Z
3,094,816
9
2010-06-22T15:54:53Z
[ "python", "regex", "string" ]
How do I remove a character from an element in a list? Example: ``` mylist = ['12:01', '12:02'] ``` I want to remove the colon from the time stamps in a file, so I can more easily convert them to a 24hour time. Right now I am trying to loop over the elements in the list and search for the one's containing a colon an...
The list comprehension solution is the most Pythonic one, but, there's an important twist: ``` mylist[:] = [s.replace(':', '') for s in mylist] ``` If you assign to `mylist`, the barename, as in the other answer, rather than to `mylist[:]`, the "whole-list slice", as I recommend, you're really doing something very di...
does write mode create a new file if not existing?
3,094,986
18
2010-06-22T16:15:38Z
3,095,017
20
2010-06-22T16:19:14Z
[ "python", "file-io" ]
I'm trying to write to a file that does not already exist using a file context manager. ``` a=open ('C:/c.txt' , 'w') ``` The above does not succeed. How would I create a file for writing if it does already exist?
Yes, `'w'` is specified as creating a new file -- as [the docs](http://docs.python.org/library/functions.html?highlight=open#open) put it, > 'w' for writing (truncating the file > if it already exists), (clearly inferring it's allowed to not already exist). Please show the exact traceback, not just your own summary o...
inserting newlines in xml file generated via xml.etree.ElementTree in python
3,095,434
17
2010-06-22T17:12:47Z
3,095,723
8
2010-06-22T17:56:03Z
[ "python", "xml" ]
I have created a xml file using xml.etree.ElementTree in python. I then use ``` tree.write(filename, "UTF-8") ``` to write out the document to a file. But when I open filename using a text editor (vi on linux), there are no newlines between the tags. Everything is one big line How can I write out the document in a ...
There is no pretty printing support in ElementTree, but you can utilize other XML modules. For example, [`xml.dom.minidom.Node.toprettyxml()`](http://docs.python.org/library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml): > `Node.toprettyxml([indent=""[, newl=""[, encoding=""]]])` > > Return a pretty-printed ...
inserting newlines in xml file generated via xml.etree.ElementTree in python
3,095,434
17
2010-06-22T17:12:47Z
3,100,114
12
2010-06-23T08:39:02Z
[ "python", "xml" ]
I have created a xml file using xml.etree.ElementTree in python. I then use ``` tree.write(filename, "UTF-8") ``` to write out the document to a file. But when I open filename using a text editor (vi on linux), there are no newlines between the tags. Everything is one big line How can I write out the document in a ...
The easiest solution I think is switching to the [lxml](http://lxml.de/) library. In most circumstances you can just change your import from `import xml.etree.ElementTree as etree` to `from lxml import etree` or similar. You can then use the `pretty_print` option when serializing: ``` tree.write(filename, pretty_prin...
inserting newlines in xml file generated via xml.etree.ElementTree in python
3,095,434
17
2010-06-22T17:12:47Z
33,956,544
7
2015-11-27T11:37:46Z
[ "python", "xml" ]
I have created a xml file using xml.etree.ElementTree in python. I then use ``` tree.write(filename, "UTF-8") ``` to write out the document to a file. But when I open filename using a text editor (vi on linux), there are no newlines between the tags. Everything is one big line How can I write out the document in a ...
I found a new way to avoid new libraries and reparsing the xml. You just need to pass your root element to this function (see below explanation): ``` def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not...
How to run Django's test database only in memory?
3,096,148
107
2010-06-22T18:45:20Z
3,096,410
19
2010-06-22T19:22:17Z
[ "python", "mysql", "django", "unit-testing" ]
My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an [SSD](http://en.wikipedia.org/wiki/Solid-state_drive), but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a si...
MySQL supports a storage engine called "MEMORY", which you can configure in your database config (`settings.py`) as such: ``` 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'OPTIONS': { "init_command": "SET storage_engine=MEMO...
How to run Django's test database only in memory?
3,096,148
107
2010-06-22T18:45:20Z
3,096,415
14
2010-06-22T19:22:58Z
[ "python", "mysql", "django", "unit-testing" ]
My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an [SSD](http://en.wikipedia.org/wiki/Solid-state_drive), but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a si...
I can't answer your main question, but there are a couple of things that you can do to speed things up. Firstly, make sure that your MySQL database is set up to use InnoDB. Then it can use transactions to rollback the state of the db before each test, which in my experience has led to a massive speed-up. You can pass ...
How to run Django's test database only in memory?
3,096,148
107
2010-06-22T18:45:20Z
3,098,182
144
2010-06-23T00:39:26Z
[ "python", "mysql", "django", "unit-testing" ]
My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an [SSD](http://en.wikipedia.org/wiki/Solid-state_drive), but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a si...
If you set your database engine to sqlite3 when you run your tests, [Django will use a in-memory database](http://docs.djangoproject.com/en/dev/ref/settings/#test-name). I'm using code like this in my `settings.py` to set the engine to sqlite when running my tests: ``` if 'test' in sys.argv: DATABASE_ENGINE = 'sq...
How to run Django's test database only in memory?
3,096,148
107
2010-06-22T18:45:20Z
4,437,821
9
2010-12-14T09:48:42Z
[ "python", "mysql", "django", "unit-testing" ]
My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an [SSD](http://en.wikipedia.org/wiki/Solid-state_drive), but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a si...
You can do double tweaking: * use transactional tables: initial fixtures state will be set using database rollback after every TestCase. * put your database data dir on ramdisk: you will gain much as far as database creation is concerned and also running test will be faster. I'm using both tricks and I'm quite happy....
How to run Django's test database only in memory?
3,096,148
107
2010-06-22T18:45:20Z
11,018,426
71
2012-06-13T15:35:29Z
[ "python", "mysql", "django", "unit-testing" ]
My Django unit tests take a long time to run, so I'm looking for ways to speed that up. I'm considering installing an [SSD](http://en.wikipedia.org/wiki/Solid-state_drive), but I know that has its downsides too. Of course, there are things I could do with my code, but I'm looking for a structural fix. Even running a si...
I usually create a separate settings file for tests and use it in test command e.g. ``` python manage.py test --settings=mysite.test_settings myapp ``` It has two benefits: 1. You don't have to check for `test` or any such magic word in sys.argv, `test_settings.py` can simply be ``` from settings import * ...
Convert time string expressed as <number>[m|h|d|s|w] to seconds in Python
3,096,860
3
2010-06-22T20:26:11Z
3,097,310
9
2010-06-22T21:33:16Z
[ "python", "datetime" ]
Is there a good method to convert a string representing time in the format of [m|h|d|s|w] (m= minutes, h=hours, d=days, s=seconds w=week) to number of seconds? I.e. ``` def convert_to_seconds(timeduration): ... convert_to_seconds("1h") -> 3600 convert_to_seconds("1d") -> 86400 ``` etc? Thanks!
Yes, there is a good **simple** method that you can use in most languages *without having to read the manual for a datetime library*. This method can also be extrapolated to ounces/pounds/tons etc etc: ``` seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800} def convert_to_seconds(s): return i...
Escape html in python?
3,096,948
4
2010-06-22T20:37:53Z
3,097,670
11
2010-06-22T22:38:56Z
[ "python", "html", "escaping" ]
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it? Example: ``` __string__ = test".jpg <img src="test".jpg"> ``` doesn't work.
If your value being escaped might contain quotes, the best thing is to use the `quoteattr` method: <http://docs.python.org/library/xml.sax.utils.html#module-xml.sax.saxutils> This is referenced right beneath the docs on the cgi.escape() method.
Escape html in python?
3,096,948
4
2010-06-22T20:37:53Z
5,072,108
9
2011-02-21T22:39:56Z
[ "python", "html", "escaping" ]
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it? Example: ``` __string__ = test".jpg <img src="test".jpg"> ``` doesn't work.
In Python 3.2 a new `html` module was introduced, which is used for escaping reserved characters from HTML markup. It has one function `html.escape(s, quote=True)`. If the optional flag quote is true, the characters `(")` and `(')` are also translated. Usage: ``` >>> import html >>> html.escape('x > 2 && x < 7') 'x ...
Difference between two time intervals in Python
3,096,953
52
2010-06-22T20:38:16Z
3,096,984
79
2010-06-22T20:42:31Z
[ "python", "time", "python-2.6" ]
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly a...
Yes, definitely [`datetime`](http://docs.python.org/library/datetime.html) is what you need here. Specifically, the `strptime` function, which parses a string into a time object. ``` from datetime import datetime s1 = '10:33:26' s2 = '11:15:49' # for example FMT = '%H:%M:%S' tdelta = datetime.strptime(s2, FMT) - datet...
Difference between two time intervals in Python
3,096,953
52
2010-06-22T20:38:16Z
3,096,991
7
2010-06-22T20:42:53Z
[ "python", "time", "python-2.6" ]
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly a...
Structure that represent time difference in Python is called [timedelta](http://docs.python.org/library/datetime.html#timedelta-objects). If you have `start_time` and `end_time` as `datetime` types you can calculate the difference using `-` operator like: ``` diff = end_time - start_time ``` you should do this before...
Difference between two time intervals in Python
3,096,953
52
2010-06-22T20:38:16Z
18,388,070
39
2013-08-22T18:23:08Z
[ "python", "time", "python-2.6" ]
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly a...
Try this -- it's efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting. ``` import time start = time.time() time.sleep(10) # or do something more productive done = time.time() elapsed = done - start print(elapsed) ```
Libraries for manipulating multivariate polynomials
3,097,464
5
2010-06-22T21:58:57Z
3,097,630
8
2010-06-22T22:30:07Z
[ "python", "math", "matlab", "numpy", "scipy" ]
I need to write some code that deals with generating and manipulating multivariable polynomials. I'll outline my task with a simplified example. Lets say I am given three expressions: 2x^2, 3y + 1, and 1z. I then need to multiply these together which would give me 6x^2yz + 2x^2z. Then I would like to find the partial ...
Sympy is perfect for this: <http://code.google.com/p/sympy/> Documentation: <http://docs.sympy.org/> Examples of differentiation from the tutorial: <http://docs.sympy.org/tutorial.html#differentiation> ``` import sympy x, y, z = sympy.symbols('xyz') p1 = 2*x*x p2 = 3*y + 1 p3 = z p4 = p1*p2*p3 print p4 print p4...
Using NumPy and Cpython with Jython
3,097,466
10
2010-06-22T21:59:03Z
3,098,074
14
2010-06-23T00:09:01Z
[ "java", "python", "numpy", "jython", "cpython" ]
I *must* use a commercial Java library, and would like to do it from Python. Jython is robust and I am fine with it being a few dot releases behind. However, I *would like* to use NumPy as well, which obviously does not work with Jython. Options like [CPype](http://jpype.blogspot.com/) and Java numeric libraries are un...
It's ironic, considering that Jython and Numeric (NumPy's ancestor) were initiated by the same developer (Jim Hugunin, who then moved on to also initiate IronPython and now holds some kind of senior architect position at Microsoft, working on all kind of dynamic languages support for .NET and Silverlight), that there's...
Python access to first element in dictionary
3,097,866
195
2010-06-22T23:24:02Z
3,097,896
249
2010-06-22T23:28:49Z
[ "python", "dictionary" ]
If `dict` is not empty, the way I use to access first element in `dict` is: ``` dict[dict.keys()[0]] ``` Is there any better way to do this?
Non-destructively you can: ``` dict.itervalues().next() ``` On Python 3 this becomes ``` next (iter (dict.values())) ``` If you want it to work in both Python 2 & 3, you can use the `six` library: ``` six.next(six.itervalues(dict)) ``` though at this point it is quite cryptic and I'd rather prefer your code. If ...
Python access to first element in dictionary
3,097,866
195
2010-06-22T23:24:02Z
3,097,995
15
2010-06-22T23:50:21Z
[ "python", "dictionary" ]
If `dict` is not empty, the way I use to access first element in `dict` is: ``` dict[dict.keys()[0]] ``` Is there any better way to do this?
As others mentioned, there is no "first item", since dictionaries have no guaranteed order (they're implemented as hash tables). If you want, for example, the value corresponding to the smallest key, `thedict[min(thedict)]` will do that. If you care about the order in which the keys were inserted, i.e., by "first" you ...
Python access to first element in dictionary
3,097,866
195
2010-06-22T23:24:02Z
3,098,077
8
2010-06-23T00:09:12Z
[ "python", "dictionary" ]
If `dict` is not empty, the way I use to access first element in `dict` is: ``` dict[dict.keys()[0]] ``` Is there any better way to do this?
Ignoring issues surrounding dict ordering, this might be better: ``` next(dict.itervalues()) ``` This way we avoid item lookup and generating a list of keys that we don't use.
Python access to first element in dictionary
3,097,866
195
2010-06-22T23:24:02Z
17,085,251
63
2013-06-13T10:54:08Z
[ "python", "dictionary" ]
If `dict` is not empty, the way I use to access first element in `dict` is: ``` dict[dict.keys()[0]] ``` Is there any better way to do this?
If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in *Python 2*: ``` my_dict.keys()[0] -> key of "first" element my_dict.values()[0] -> value of "first" element my_dict.items()[0] -> (key, value) tuple of "first" element ``` Pleas...
Python access to first element in dictionary
3,097,866
195
2010-06-22T23:24:02Z
26,053,339
16
2014-09-26T06:27:44Z
[ "python", "dictionary" ]
If `dict` is not empty, the way I use to access first element in `dict` is: ``` dict[dict.keys()[0]] ``` Is there any better way to do this?
In python3, The way : ``` dict.keys() ``` return a value in type : dict\_keys(), we'll got an error when got 1st member of keys of dict by this way: ``` dict.keys()[0] TypeError: 'dict_keys' object does not support indexing ``` Finally, I convert dict.keys() to list @1st, and got 1st member by list splice method: ...
Time to decimal time in Python
3,098,248
5
2010-06-23T01:04:25Z
3,098,273
7
2010-06-23T01:12:21Z
[ "python", "time" ]
Which Python datetime or time method should I use to convert time in HH:MM:SS to decimal time in seconds? The times represent durations of time (most are less than a minute) and are not connected to a date.
``` t = "1:12:23" (h, m, s) = t.split(':') result = int(h) * 3600 + int(m) * 60 + int(s) ```
Input from 20+ microphones
3,098,581
9
2010-06-23T02:41:20Z
3,099,720
7
2010-06-23T07:29:32Z
[ "python", "audio", "usb", "microphone", "libusb" ]
I've been asked (if it's possible) to write a program monitoring the input of at least 20 microphones, on a single computer. Currently I'm prototyping in python (2.6), on a Ubuntu system using Alsa. My attempts so far have created quite a few questions... Ubuntu is a requirement, Alsa isn't, and python is an ideal. ...
The definition of "monitor" is a very big variable here. Monitor could mean "record to disk", "detect volume levels above a particular threshold" or "perform higher level analysis in the frequency domain (i.e. conventional signal processing)." These three have very different implications for CPU usage and the feasibili...
How to discover current role in Python Fabric
3,098,912
20
2010-06-23T04:20:12Z
3,102,732
16
2010-06-23T14:51:40Z
[ "python", "fabric" ]
This is a very [Fabric](http://docs.fabfile.org) specific question, but more experienced python hackers might be able to answer this, even if they don't know Fabric. I am trying to specify different behaviour in a command depending on which role it is running for, i.e.: ``` def restart(): if (SERVERTYPE == "APACH...
For everyone else ever with this question, here is my solution: The key was finding env.host\_string. This is how I restart different types of servers with one command: ``` env.roledefs = { 'apache': ['xxx.xxx.com'], 'APE': ['yyy.xxx.com'] } def apache(): env.roles = ['apache'] ... def restart(): ...
How to discover current role in Python Fabric
3,098,912
20
2010-06-23T04:20:12Z
9,673,778
9
2012-03-12T19:46:46Z
[ "python", "fabric" ]
This is a very [Fabric](http://docs.fabfile.org) specific question, but more experienced python hackers might be able to answer this, even if they don't know Fabric. I am trying to specify different behaviour in a command depending on which role it is running for, i.e.: ``` def restart(): if (SERVERTYPE == "APACH...
I didn't test it, but might work: ``` def _get_current_role(): for role in env.roledefs.keys(): if env.host_string in env.roledefs[role]: return role return None ```