title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Introducing Python | 19,654 | <p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p>
<p>But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now.</p>
<p>How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company.</p>
<p>Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them.</p>
| 5 | 2008-08-21T11:48:03Z | 19,715 | <p>I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive results. In addition, I used Python for all of my small throwaway assignments ("can you parse the stats in these files into a CSV file organized by date and site?", etc) and had a quick turnaround time on all of them.</p>
<p>I also evangelized Python a bit; I went out of my way to NOT be obnoxious about it, but I'd occasionally describe why I liked it so much, talked about the personal projects I use it for in my free time and why it's awesome for me, etc.</p>
<p>Eventually we started another project and I convinced everyone to use Python for it. I took care to point everyone to a lot of documentation, including the specific webpages relating to what they were working on, and every time they had a question, I'd explain how to do things properly by explaining the Pythonic approach to things, etc.</p>
<p>This has worked really well. However, this might be somewhat different than what you're describing. In my case I started with moderately small projects and Python is only being used for new projects. Also, none of my co-workers were really Perl or PHP gurus; they all knew those languages and had been using them for awhile, but it didn't take much effort for them to become more productive in Python than they'd been before.</p>
<p>So if you're talking about new projects with people who currently use PHP but aren't super-experts and don't love that language, then I think switching to Python is a no-brainer. However, if you're talking about working with a large existing PHP code base with a lot of very experienced PHP programmers who are happy with their current setup, then switching languages is probably not a good idea. You're probably somewhere in between, so you'll have to weigh the tradeoffs; hopefully my answer will help you do that.</p>
| 13 | 2008-08-21T12:25:21Z | [
"php",
"python"
] |
Introducing Python | 19,654 | <p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p>
<p>But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now.</p>
<p>How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company.</p>
<p>Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them.</p>
| 5 | 2008-08-21T11:48:03Z | 19,943 | <p>I love Python and Django, and use both to develop the our core webapps.</p>
<p>That said, it's hard to make a business case for switching at this point. Specifically:</p>
<ul>
<li>Any new platform is risky compared to staying with the tried and true</li>
<li>You'll have the developer fragmentation you mentioned</li>
<li>It's far easier to find PHP programmers than python programmers</li>
</ul>
<p>Moreover, as other posters have mention, if the issue is more with spaghetti code than PHP itself, there are plenty of nice PHP frameworks that could be used to refactor the code.</p>
<p>That said, if this developer is excited about python, stopping them outright is probably demoralizing. My suggestion would be to encourage them to develop in python, but not the mission critical parts of the app. Instead they could write some utility scripts, some small internal application that needs doing, etc.</p>
<p>In conclusion: I don't recommend switching from PHP, but I do recommend accommodating the developer's interest in some way at work.</p>
| 0 | 2008-08-21T13:47:40Z | [
"php",
"python"
] |
Introducing Python | 19,654 | <p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p>
<p>But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now.</p>
<p>How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company.</p>
<p>Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them.</p>
| 5 | 2008-08-21T11:48:03Z | 19,968 | <p>It's really all about schedules. To me the break should be with a specific project. If you decide your direction is Django then start new projects with that. Before you start a new project with a new language/framework, either make sure that you have scheduled time to get up to speed in this new direction, or get up to speed before using on new projects.</p>
<p>I would avoid going with a tool of the month. Make sure you want it to be your direction and commit some time/resources to learning enough to make a good decision.</p>
| 1 | 2008-08-21T13:57:41Z | [
"php",
"python"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 20,065 | <p>Use <code>optparse</code> which comes with the standard library. For example:</p>
<pre><code>#!/usr/bin/env python
import optparse
def main():
p = optparse.OptionParser()
p.add_option('--person', '-p', default="world")
options, arguments = p.parse_args()
print 'Hello %s' % options.person
if __name__ == '__main__':
main()
</code></pre>
<p>Source: <a href="http://www.ibm.com/developerworks/aix/library/au-pythocli/" rel="nofollow">Using Python to create UNIX command line tools</a></p>
<p>However as of Python 2.7 optparse is deprecated, see: <a href="http://stackoverflow.com/q/3217673/55075">Why use argparse rather than optparse?</a></p>
| 13 | 2008-08-21T14:25:19Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 20,069 | <p>Pretty much everybody is using <a href="http://python.active-venture.com/lib/module-getopt.html" rel="nofollow">getopt</a></p>
<p>Here is the example code for the doc :</p>
<pre><code>import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-o", "--output"):
output = a
</code></pre>
<p>So in a word, here is how it works.</p>
<p>You've got two types of options. Those who are receiving arguments, and those who are
just like switches.</p>
<p><code>sys.argv</code> is pretty much your <code>char** argv</code> in C. Like in C you skip the first element which is the name of your program and parse only the arguments : <code>sys.argv[1:]</code></p>
<p><code>Getopt.getopt</code> will parse it according to the rule you give in argument.</p>
<p><code>"ho:v"</code> here describes the short arguments : <code>-ONELETTER</code>. The <code>:</code> means that <code>-o</code> accepts one argument.</p>
<p>Finally <code>["help", "output="]</code> describes long arguments ( <code>--MORETHANONELETTER</code> ).
The <code>=</code> after output once again means that output accepts one arguments.</p>
<p>The result is a list of couple (option,argument)</p>
<p>If an option doesn't accept any argument (like <code>--help</code> here) the <code>arg</code> part is an empty string.
You then usually want to loop on this list and test the option name as in the example.</p>
<p>I hope this helped you.</p>
| 14 | 2008-08-21T14:26:57Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 20,169 | <p>Just in case you might need to, this may help if you need to <strong>grab</strong> unicode arguments on Win32 (2K, XP etc):</p>
<pre><code>
from ctypes import *
def wmain(argc, argv):
print argc
for i in argv:
print i
return 0
def startup():
size = c_int()
ptr = windll.shell32.CommandLineToArgvW(windll.kernel32.GetCommandLineW(), byref(size))
ref = c_wchar_p * size.value
raw = ref.from_address(ptr)
args = [arg for arg in raw]
windll.kernel32.LocalFree(ptr)
exit(wmain(len(args), args))
startup()
</code></pre>
| 4 | 2008-08-21T14:59:54Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 20,222 | <p>I prefer optparse to getopt. It's very declarative: you tell it the names of the options and the effects they should have (e.g., setting a boolean field), and it hands you back a dictionary populated according to your specifications.</p>
<p><a href="http://docs.python.org/lib/module-optparse.html" rel="nofollow">http://docs.python.org/lib/module-optparse.html</a></p>
| 2 | 2008-08-21T15:22:20Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 26,910 | <p><strong>This answer suggests <code>optparse</code> which is appropriate for older Python versions. For Python 2.7 and above, <code>argparse</code> replaces <code>optparse</code>. See <a href="http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse">this answer</a> for more information.</strong></p>
<p>As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.</p>
<p>optparse, while being a bit more verbose, is much better structured and simpler to extend later on.</p>
<p>Here's a typical line to add an option to your parser:</p>
<pre><code>parser.add_option('-q', '--query',
action="store", dest="query",
help="query string", default="spam")
</code></pre>
<p>It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option.</p>
<p>Usually you parse your arguments with:</p>
<pre><code>options, args = parser.parse_args()
</code></pre>
<p>This will, by default, parse the standard arguments passed to the script (sys.argv[1:])</p>
<p>options.query will then be set to the value you passed to the script.</p>
<p>You create a parser simply by doing</p>
<pre><code>parser = optparse.OptionParser()
</code></pre>
<p>These are all the basics you need. Here's a complete Python script that shows this:</p>
<pre><code>import optparse
parser = optparse.OptionParser()
parser.add_option('-q', '--query',
action="store", dest="query",
help="query string", default="spam")
options, args = parser.parse_args()
print 'Query string:', options.query
</code></pre>
<p>5 lines of python that show you the basics.</p>
<p>Save it in sample.py, and run it once with</p>
<pre><code>python sample.py
</code></pre>
<p>and once with</p>
<pre><code>python sample.py --query myquery
</code></pre>
<p>Beyond that, you will find that optparse is very easy to extend.
In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py">browse around in my repository</a> for the main class, as well as <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py">a class that uses it and the option parser</a></p>
| 85 | 2008-08-25T21:11:03Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 30,973 | <p>I think the best way for larger projects is optparse, but if you are looking for an easy way, maybe <a href="http://werkzeug.pocoo.org/documentation/script" rel="nofollow">http://werkzeug.pocoo.org/documentation/script</a> is something for you.</p>
<pre><code>from werkzeug import script
# actions go here
def action_foo(name=""):
"""action foo does foo"""
pass
def action_bar(id=0, title="default title"):
"""action bar does bar"""
pass
if __name__ == '__main__':
script.run()
</code></pre>
<p>So basically every function action_* is exposed to the command line and a nice
help message is generated for free. </p>
<pre><code>python foo.py
usage: foo.py <action> [<options>]
foo.py --help
actions:
bar:
action bar does bar
--id integer 0
--title string default title
foo:
action foo does foo
--name string
</code></pre>
| 2 | 2008-08-27T19:27:06Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 979,871 | <p>The new hip way is <code>argparse</code> for <a href="http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html">these</a> reasons. argparse > optparse > getopt</p>
<p><strong>update:</strong> As of py2.7 <a href="http://docs.python.org/library/argparse.html">argparse</a> is part of the standard library and <a href="http://docs.python.org/library/optparse.html">optparse</a> is deprecated.</p>
| 32 | 2009-06-11T07:54:53Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 11,271,779 | <p><a href="https://github.com/muromec/consoleargs" rel="nofollow">consoleargs</a> deserves to be mentioned here. It is very easy to use. Check it out:</p>
<pre><code>from consoleargs import command
@command
def main(url, name=None):
"""
:param url: Remote URL
:param name: File name
"""
print """Downloading url '%r' into file '%r'""" % (url, name)
if __name__ == '__main__':
main()
</code></pre>
<p>Now in console:</p>
<pre><code>% python demo.py --help
Usage: demo.py URL [OPTIONS]
URL: Remote URL
Options:
--name -n File name
% python demo.py http://www.google.com/
Downloading url ''http://www.google.com/'' into file 'None'
% python demo.py http://www.google.com/ --name=index.html
Downloading url ''http://www.google.com/'' into file ''index.html''
</code></pre>
| 1 | 2012-06-30T05:43:02Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 16,377,263 | <p>Since 2012 Python has a very easy, powerful and really <em>cool</em> module for argument parsing called <a href="https://github.com/docopt/docopt" rel="nofollow">docopt</a>. It works with Python 2.6 to 3.5 and needs no installation (just copy it). Here is an example taken from it's documentation: </p>
<pre><code>"""Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)
</code></pre>
<p>So this is it: one line of code plus your doc string which <em>is</em> essential. I told you it's cool, didn't I ;-)</p>
| 37 | 2013-05-04T17:51:38Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 27,069,329 | <p>I prefer <a href="http://click.pocoo.org/" rel="nofollow">Click</a>. It abstracts managing options and allows "(...) creating beautiful command line interfaces in a composable way with as little code as necessary".</p>
<p>Here's example usage:</p>
<pre><code>import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
hello()
</code></pre>
<p>It also automatically generates nicely formatted help pages:</p>
<pre><code>$ python hello.py --help
Usage: hello.py [OPTIONS]
Simple program that greets NAME for a total of COUNT times.
Options:
--count INTEGER Number of greetings.
--name TEXT The person to greet.
--help Show this message and exit.
</code></pre>
| 5 | 2014-11-21T20:00:04Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 30,493,366 | <p>Other answers do mention that <code>argparse</code> is the way to go for new Python, but do not give usage examples. For completeness, here is a short summary of how to use argparse:</p>
<p><strong>1) Initialize</strong></p>
<pre><code>import argparse
# Instantiate the parser
parser = argparse.ArgumentParser(description='Optional app description')
</code></pre>
<p><strong>2) Add Arguments</strong></p>
<pre><code># Required positional argument
parser.add_argument('pos_arg', type=int,
help='A required integer positional argument')
# Optional positional argument
parser.add_argument('opt_pos_arg', type=int, nargs='?',
help='An optional integer positional argument')
# Optional argument
parser.add_argument('--opt_arg', type=int,
help='An optional integer argument')
# Switch
parser.add_argument('--switch', action='store_true',
help='A boolean switch')
</code></pre>
<p><strong>3) Parse</strong></p>
<pre><code>args = parser.parse_args()
</code></pre>
<p><strong>4) Access</strong></p>
<pre><code>print("Argument values:")
print(args.pos_arg)
print(args.opt_pos_arg)
print(args.opt_arg)
print(args.switch)
</code></pre>
<p><strong>5) Check Values</strong></p>
<pre><code>if args.pos_arg > 10:
parser.error("pos_arg cannot be larger than 10")
</code></pre>
<h2>Usage</h2>
<p><strong>Correct use:</strong></p>
<pre><code>$ ./app 1 2 --opt_arg 3 --switch
Argument values:
1
2
3
True
</code></pre>
<p><strong>Incorrect arguments:</strong></p>
<pre><code>$ ./app foo 2 --opt_arg 3 --switch
usage: convert [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
app: error: argument pos_arg: invalid int value: 'foo'
$ ./app 11 2 --opt_arg 3
Argument values:
11
2
3
False
usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
convert: error: pos_arg cannot be larger than 10
</code></pre>
<p><strong>Full help:</strong></p>
<pre><code>$ ./app -h
usage: app [-h] [--opt_arg OPT_ARG] [--switch] pos_arg [opt_pos_arg]
Optional app description
positional arguments:
pos_arg A required integer positional argument
opt_pos_arg An optional integer positional argument
optional arguments:
-h, --help show this help message and exit
--opt_arg OPT_ARG An optional integer argument
--switch A boolean switch
</code></pre>
| 27 | 2015-05-27T21:21:26Z | [
"python",
"command-line",
"command-line-arguments"
] |
What's the best way to grab/parse command line arguments passed to a Python script? | 20,063 | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| 84 | 2008-08-21T14:24:41Z | 36,516,929 | <p>Here's a method, not a library, which seems to work for me.</p>
<p>The goals here are to be terse, each argument parsed by a single line, the args line up for readability, the code is simple and doesn't depend on any special modules (only os + sys), warns about missing or unknown arguments gracefully, use a simple for/range() loop, and works across python 2.x and 3.x</p>
<p>Shown are two toggle flags (-d, -v), and two values controlled by arguments (-i xxx and -o xxx).</p>
<pre><code>import os,sys
def HelpAndExit():
print("<<your help output goes here>>")
sys.exit(1)
def Fatal(msg):
sys.stderr.write("%s: %s\n" % (os.path.basename(sys.argv[0]), msg))
sys.exit(1)
def NextArg(i):
'''Return the next command line argument (if there is one)'''
if ((i+1) >= len(sys.argv)):
Fatal("'%s' expected an argument" % sys.argv[i])
return(1, sys.argv[i+1])
### MAIN
if __name__=='__main__':
verbose = 0
debug = 0
infile = "infile"
outfile = "outfile"
# Parse command line
skip = 0
for i in range(1, len(sys.argv)):
if not skip:
if sys.argv[i][:2] == "-d": debug ^= 1
elif sys.argv[i][:2] == "-v": verbose ^= 1
elif sys.argv[i][:2] == "-i": (skip,infile) = NextArg(i)
elif sys.argv[i][:2] == "-o": (skip,outfile) = NextArg(i)
elif sys.argv[i][:2] == "-h": HelpAndExit()
elif sys.argv[i][:1] == "-": Fatal("'%s' unknown argument" % sys.argv[i])
else: Fatal("'%s' unexpected" % sys.argv[i])
else: skip = 0
print("%d,%d,%s,%s" % (debug,verbose,infile,outfile))
</code></pre>
<p>The goal of NextArg() is to return the next argument while checking for missing data, and 'skip' skips the loop when NextArg() is used, keeping the flag parsing down to one liners.</p>
| -1 | 2016-04-09T12:45:12Z | [
"python",
"command-line",
"command-line-arguments"
] |
Find broken symlinks with Python | 20,794 | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| 13 | 2008-08-21T19:00:52Z | 20,843 | <p>Can I mention testing for hardlinks without python? /bin/test has the FILE1 -ef FILE2 condition that is true when files share an inode.</p>
<p>Therefore, something like <code>find . -type f -exec test \{} -ef /path/to/file \; -print</code> works for hard link testing to a specific file.</p>
<p>Which brings me to reading <code>man test</code> and the mentions of <code>-L</code> and <code>-h</code> which both work on one file and return true if that file is a symbolic link, however that doesn't tell you if the target is missing.</p>
<p>I did find that <code>head -0 FILE1</code> would return an exit code of <code>0</code> if the file can be opened and a <code>1</code> if it cannot, which in the case of a symbolic link to a regular file works as a test for whether it's target can be read.</p>
| 3 | 2008-08-21T19:13:46Z | [
"python",
"linux",
"symlink"
] |
Find broken symlinks with Python | 20,794 | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| 13 | 2008-08-21T19:00:52Z | 20,845 | <p>I'm not a python guy but it looks like os.readlink()? The logic I would use in perl is to use readlink() to find the target and the use stat() to test to see if the target exists.</p>
<p>Edit: I banged out some perl that demos readlink. I believe perl's stat and readlink and python's os.stat() and os.readlink()are both wrappers for the system calls, so this should translate reasonable well as proof of concept code:</p>
<pre><code>wembley 0 /home/jj33/swap > cat p
my $f = shift;
while (my $l = readlink($f)) {
print "$f -> $l\n";
$f = $l;
}
if (!-e $f) {
print "$f doesn't exist\n";
}
wembley 0 /home/jj33/swap > ls -l | grep ^l
lrwxrwxrwx 1 jj33 users 17 Aug 21 14:30 link -> non-existant-file
lrwxrwxrwx 1 root users 31 Oct 10 2007 mm -> ../systems/mm/20071009-rewrite//
lrwxrwxrwx 1 jj33 users 2 Aug 21 14:34 mmm -> mm/
wembley 0 /home/jj33/swap > perl p mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p mmm
mmm -> mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p link
link -> non-existant-file
non-existant-file doesn't exist
wembley 0 /home/jj33/swap >
</code></pre>
| 1 | 2008-08-21T19:14:01Z | [
"python",
"linux",
"symlink"
] |
Find broken symlinks with Python | 20,794 | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| 13 | 2008-08-21T19:00:52Z | 20,848 | <p><a href="https://docs.python.org/2/library/os.html#os.lstat" rel="nofollow">os.lstat()</a> may be helpful. If lstat() succeeds and stat() fails, then it's probably a broken link.</p>
| 11 | 2008-08-21T19:15:33Z | [
"python",
"linux",
"symlink"
] |
Find broken symlinks with Python | 20,794 | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| 13 | 2008-08-21T19:00:52Z | 20,859 | <p><a href="http://docs.python.org/lib/module-os.path.html" rel="nofollow">os.path</a></p>
<p>You may try using realpath() to get what the symlink points to, then trying to determine if it's a valid file using is file.</p>
<p>(I'm not able to try that out at the moment, so you'll have to play around with it and see what you get)</p>
| 2 | 2008-08-21T19:19:24Z | [
"python",
"linux",
"symlink"
] |
Find broken symlinks with Python | 20,794 | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| 13 | 2008-08-21T19:00:52Z | 26,957 | <p>A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code.</p>
<p><strong>A typical mistake is to write something like</strong>:</p>
<pre><code>if os.path.exists(path):
os.unlink(path)
</code></pre>
<p>The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months)</p>
<p>So, in your particular case, I would probably do:</p>
<pre><code>try:
os.stat(path)
except OSError, e:
if e.errno == errno.ENOENT:
print 'path %s does not exist or is a broken symlink' % path
else:
raise e
</code></pre>
<p>The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink.</p>
<p>So, I guess you have no choice than to break the atomicity, and do something like</p>
<pre><code>if not os.path.exists(os.readlink(path)):
print 'path %s is a broken symlink' % path
</code></pre>
| 18 | 2008-08-25T21:32:20Z | [
"python",
"linux",
"symlink"
] |
Find broken symlinks with Python | 20,794 | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| 13 | 2008-08-21T19:00:52Z | 31,102,280 | <p>This is not atomic but it works.</p>
<p><code>os.path.islink(filename) and not os.path.exists(filename)</code></p>
<p>Indeed by <a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">RTFM</a>
(reading the fantastic manual) we see</p>
<blockquote>
<p>os.path.exists(path)</p>
<p>Return True if path refers to an existing path. Returns False for broken symbolic links.</p>
</blockquote>
<p>It also says:</p>
<blockquote>
<p>On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.</p>
</blockquote>
<p>So if you are worried about permissions, you should add other clauses.</p>
| 4 | 2015-06-28T16:49:13Z | [
"python",
"linux",
"symlink"
] |
updating an auto_now DateTimeField in a parent model w/ Django | 20,927 | <p>I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:</p>
<pre><code>def save(self):
super(Attachment, self).save()
self.message.updated = self.updated
</code></pre>
<p>Will this work, and if you can explain it to me, why? If not, how would I accomplish this?</p>
| 6 | 2008-08-21T19:41:57Z | 20,983 | <p>You would also need to then save the message. Then it that should work.</p>
| 5 | 2008-08-21T19:57:36Z | [
"python",
"database",
"django",
"orm"
] |
updating an auto_now DateTimeField in a parent model w/ Django | 20,927 | <p>I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:</p>
<pre><code>def save(self):
super(Attachment, self).save()
self.message.updated = self.updated
</code></pre>
<p>Will this work, and if you can explain it to me, why? If not, how would I accomplish this?</p>
| 6 | 2008-08-21T19:41:57Z | 72,359 | <p>DateTime fields with auto_now are automatically updated upon calling <code>save()</code>, so you do not need to update them manually. Django will do this work for you.</p>
| 1 | 2008-09-16T13:44:51Z | [
"python",
"database",
"django",
"orm"
] |
updating an auto_now DateTimeField in a parent model w/ Django | 20,927 | <p>I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:</p>
<pre><code>def save(self):
super(Attachment, self).save()
self.message.updated = self.updated
</code></pre>
<p>Will this work, and if you can explain it to me, why? If not, how would I accomplish this?</p>
| 6 | 2008-08-21T19:41:57Z | 33,449,486 | <p>Proper version to work is: (attention to last line <code>self.message.save()</code>)</p>
<pre><code>class Message(models.Model):
updated = models.DateTimeField(auto_now = True)
...
class Attachment(models.Model):
updated = models.DateTimeField(auto_now = True)
message = models.ForeignKey(Message)
def save(self):
super(Attachment, self).save()
self.message.save()
</code></pre>
| 0 | 2015-10-31T08:11:30Z | [
"python",
"database",
"django",
"orm"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 21,468 | <p>From the <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices" rel="nofollow">Django documentation</a>:</p>
<pre><code>MAYBECHOICE = (
('y', 'Yes'),
('n', 'No'),
('u', 'Unknown'),
)
</code></pre>
<p>And you define a charfield in your model :</p>
<pre><code>married = models.CharField(max_length=1, choices=MAYBECHOICE)
</code></pre>
<p>You can do the same with integer fields if you don't like to have letters
in your db.</p>
<p>In that case, rewrite your choices:</p>
<pre><code>MAYBECHOICE = (
(0, 'Yes'),
(1, 'No'),
(2, 'Unknown'),
)
</code></pre>
| 75 | 2008-08-21T23:54:52Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 33,932 | <p>Using the <code>choices</code> parameter won't use the ENUM db type; it will just create a VARCHAR or INTEGER, depending on whether you use <code>choices</code> with a CharField or IntegerField. Generally, this is just fine. If it's important to you that the ENUM type is used at the database level, you have three options:</p>
<ol>
<li>Use "./manage.py sql appname" to see the SQL Django generates, manually modify it to use the ENUM type, and run it yourself. If you create the table manually first, "./manage.py syncdb" won't mess with it.</li>
<li>If you don't want to do this manually every time you generate your DB, put some custom SQL in appname/sql/modelname.sql to perform the appropriate ALTER TABLE command.</li>
<li>Create a <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">custom field type</a> and define the db_type method appropriately.</li>
</ol>
<p>With any of these options, it would be your responsibility to deal with the implications for cross-database portability. In option 2, you could use <a href="http://www.djangoproject.com/documentation/model-api/#database-backend-specific-sql-data" rel="nofollow">database-backend-specific custom SQL</a> to ensure your ALTER TABLE is only run on MySQL. In option 3, your db_type method would need to check the database engine and set the db column type to a type that actually exists in that database.</p>
<p><strong>UPDATE</strong>: Since the migrations framework was added in Django 1.7, options 1 and 2 above are entirely obsolete. Option 3 was always the best option anyway. The new version of options 1/2 would involve a complex custom migration using <code>SeparateDatabaseAndState</code> -- but really you want option 3.</p>
| 26 | 2008-08-29T03:57:14Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 334,932 | <p>If you really want to use your databases ENUM type:</p>
<ol>
<li>Use Django 1.x</li>
<li>Recognize your application will only work on some databases.</li>
<li>Puzzle through this documentation page:<a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields">http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields</a></li>
</ol>
<p>Good luck!</p>
| 6 | 2008-12-02T18:21:16Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 1,530,858 | <pre><code>from django.db import models
class EnumField(models.Field):
"""
A field class that maps to MySQL's ENUM type.
Usage:
class Card(models.Model):
suit = EnumField(values=('Clubs', 'Diamonds', 'Spades', 'Hearts'))
c = Card()
c.suit = 'Clubs'
c.save()
"""
def __init__(self, *args, **kwargs):
self.values = kwargs.pop('values')
kwargs['choices'] = [(v, v) for v in self.values]
kwargs['default'] = self.values[0]
super(EnumField, self).__init__(*args, **kwargs)
def db_type(self):
return "enum({0})".format( ','.join("'%s'" % v for v in self.values) )
</code></pre>
| 31 | 2009-10-07T10:47:46Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 13,089,465 | <p><a href="http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/">http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/</a></p>
<blockquote>
<pre><code>class Entry(models.Model):
LIVE_STATUS = 1
DRAFT_STATUS = 2
HIDDEN_STATUS = 3
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(DRAFT_STATUS, 'Draft'),
(HIDDEN_STATUS, 'Hidden'),
)
# ...some other fields here...
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)
live_entries = Entry.objects.filter(status=Entry.LIVE_STATUS)
draft_entries = Entry.objects.filter(status=Entry.DRAFT_STATUS)
if entry_object.status == Entry.LIVE_STATUS:
</code></pre>
</blockquote>
<p>This is another nice and easy way of implementing enums although it doesn't really save enums in the database.</p>
<p>However it does allow you to reference the 'label' whenever querying or specifying defaults as opposed to the top-rated answer where you have to use the 'value' (which may be a number).</p>
| 6 | 2012-10-26T15:03:50Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 19,040,441 | <p>Setting <code>choices</code> on the field will allow some validation on the Django end, but it <em>won't</em> define any form of an enumerated type on the database end.</p>
<p>As others have mentioned, the solution is to specify <a href="https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#django.db.models.Field.db_type"><code>db_type</code></a> on a custom field.</p>
<p>If you're using a SQL backend (e.g. MySQL), you can do this like so:</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
class EnumField(models.Field):
def __init__(self, *args, **kwargs):
super(EnumField, self).__init__(*args, **kwargs)
assert self.choices, "Need choices for enumeration"
def db_type(self, connection):
if not all(isinstance(col, basestring) for col, _ in self.choices):
raise ValueError("MySQL ENUM values should be strings")
return "ENUM({})".format(','.join("'{}'".format(col)
for col, _ in self.choices))
class IceCreamFlavor(EnumField, models.CharField):
def __init__(self, *args, **kwargs):
flavors = [('chocolate', 'Chocolate'),
('vanilla', 'Vanilla'),
]
super(IceCreamFlavor, self).__init__(*args, choices=flavors, **kwargs)
class IceCream(models.Model):
price = models.DecimalField(max_digits=4, decimal_places=2)
flavor = IceCreamFlavor(max_length=20)
</code></pre>
<p>Run <code>syncdb</code>, and inspect your table to see that the <code>ENUM</code> was created properly.</p>
<pre class="lang-sql prettyprint-override"><code>mysql> SHOW COLUMNS IN icecream;
+--------+-----------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| price | decimal(4,2) | NO | | NULL | |
| flavor | enum('chocolate','vanilla') | NO | | NULL | |
+--------+-----------------------------+------+-----+---------+----------------+
</code></pre>
| 6 | 2013-09-26T23:38:42Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 22,155,357 | <p>A the top of your models.py file, add this line after you do your imports:</p>
<pre><code> enum = lambda *l: [(s,_(s)) for s in l]
</code></pre>
| 0 | 2014-03-03T19:18:56Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Specifying a mySQL ENUM in a Django model | 21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| 65 | 2008-08-21T23:48:08Z | 28,408,589 | <p>There're currently two github projects based on adding these, though I've not looked into exactly how they're implemented:</p>
<ol>
<li><a href="https://github.com/5monkeys/django-enumfield" rel="nofollow">Django-EnumField</a>:<br>
Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. </li>
<li><a href="https://github.com/hzdg/django-enumfields" rel="nofollow">Django-EnumFields</a>:<br>
This package lets you use real Python (PEP435-style) enums with Django.</li>
</ol>
<p>I don't think either use DB enum types, but they are <a href="https://github.com/5monkeys/django-enumfield/issues/18" rel="nofollow">in the works</a> for first one.</p>
| 3 | 2015-02-09T11:23:31Z | [
"python",
"mysql",
"django",
"django-models",
"enums"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 21,937 | <p>I think the article "<a href="http://www.ibm.com/developerworks/java/library/j-jtp10283/">Java theory and practice: A brief history of garbage collection</a>" from IBM should help explain some of the questions you have.</p>
| 8 | 2008-08-22T07:40:12Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 21,964 | <p>There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically...</p>
<p>Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this.</p>
<p>Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...</p>
| 40 | 2008-08-22T09:10:06Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 22,219 | <p>Darren Thomas gives a good answer. However, one big difference between the Java and Python approaches is that with reference counting in the common case (no circular references) objects are cleaned up immediately rather than at some indeterminate later date.</p>
<p>For example, I can write sloppy, non-portable code in CPython such as</p>
<pre><code>def parse_some_attrs(fname):
return open(fname).read().split("~~~")[2:4]
</code></pre>
<p>and the file descriptor for that file I opened will be cleaned up immediately because as soon as the reference to the open file goes away, the file is garbage collected and the file descriptor is freed. Of course, if I run Jython or IronPython or possibly PyPy, then the garbage collector won't necessarily run until much later; possibly I'll run out of file descriptors first and my program will crash.</p>
<p>So you SHOULD be writing code that looks like</p>
<pre><code>def parse_some_attrs(fname):
with open(fname) as f:
return f.read().split("~~~")[2:4]
</code></pre>
<p>but sometimes people like to rely on reference counting to always free up their resources because it can sometimes make your code a little shorter.</p>
<p>I'd say that the best garbage collector is the one with the best performance, which currently seems to be the Java-style generational garbage collectors that can run in a separate thread and has all these crazy optimizations, etc. The differences to how you write your code should be negligible and ideally non-existent.</p>
| 11 | 2008-08-22T12:40:03Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 23,703 | <p>The latest Sun Java VM actually have multiple GC algorithms which you can tweak. The Java VM specifications intentionally omitted specifying actual GC behaviour to allow different (and multiple) GC algorithms for different VMs.</p>
<p>For example, for all the people who dislike the "stop-the-world" approach of the default Sun Java VM GC behaviour, there are VM such as <a href="http://www-01.ibm.com/software/webservers/realtime/" rel="nofollow">IBM's WebSphere Real Time</a> which allows real-time application to run on Java.</p>
<p>Since the Java VM spec is publicly available, there is (theoretically) nothing stopping anyone from implementing a Java VM that uses CPython's GC algorithm.</p>
| 2 | 2008-08-22T22:58:36Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 46,780 | <p>Reference counting is particularly difficult to do efficiently in a multi-threaded environment. I don't know how you'd even start to do it without getting into hardware assisted transactions or similar (currently) unusual atomic instructions.</p>
<p>Reference counting is easy to implement. JVMs have had a lot of money sunk into competing implementations, so it shouldn't be surprising that they implement very good solutions to very difficult problems. However, it's becoming increasingly easy to target your favourite language at the JVM.</p>
| 2 | 2008-09-05T20:03:19Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 74,327 | <p>Garbage collection is faster (more time efficient) than reference counting, if you have enough memory. For example, a copying gc traverses the "live" objects and copies them to a new space, and can reclaim all the "dead" objects in one step by marking a whole memory region. This is very efficient, <em>if</em> you have enough memory. Generational collections use the knowledge that "most objects die young"; often only a few percent of objects have to be copied.</p>
<p>[This is also the reason why gc can be faster than malloc/free]</p>
<p>Reference counting is much more space efficient than garbage collection, since it reclaims memory the very moment it gets unreachable. This is nice when you want to attach finalizers to objects (e.g. to close a file once the File object gets unreachable). A reference counting system can work even when only a few percent of the memory is free. But the management cost of having to increment and decrement counters upon each pointer assignment cost a lot of time, and some kind of garbage collection is still needed to reclaim cycles.</p>
<p>So the trade-off is clear: if you have to work in a memory-constrained environment, or if you need precise finalizers, use reference counting. If you have enough memory and need the speed, use garbage collection.</p>
| 5 | 2008-09-16T16:38:56Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 196,487 | <p>Actually reference counting and the strategies used by the Sun JVM are all different types of garbage collection algorithms.</p>
<p>There are two broad approaches for tracking down dead objects: tracing and reference counting. In tracing the GC starts from the "roots" - things like stack references, and traces all reachable (live) objects. Anything that can't be reached is considered dead. In reference counting each time a reference is modified the object's involved have their count updated. Any object whose reference count gets set to zero is considered dead.</p>
<p>With basically all GC implementations there are trade offs but tracing is usually good for high through put (i.e. fast) operation but has longer pause times (larger gaps where the UI or program may freeze up). Reference counting can operate in smaller chunks but will be slower overall. It may mean less freezes but poorer performance overall.</p>
<p>Additionally a reference counting GC requires a cycle detector to clean up any objects in a cycle that won't be caught by their reference count alone. Perl 5 didn't have a cycle detector in its GC implementation and could leak memory that was cyclic.</p>
<p>Research has also been done to get the best of both worlds (low pause times, high throughput):
<a href="http://cs.anu.edu.au/~Steve.Blackburn/pubs/papers/urc-oopsla-2003.pdf">http://cs.anu.edu.au/~Steve.Blackburn/pubs/papers/urc-oopsla-2003.pdf</a></p>
| 22 | 2008-10-13T01:42:10Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 1,604,520 | <p>Late in the game, but I think one significant rationale for RC in python is its simplicity. See this <a href="http://mail.python.org/pipermail/python-list/2005-October/921938.html" rel="nofollow">email by Alex Martelli</a>, for example.</p>
<p>(I could not find a link outside google cache, the email date from 13th october 2005 on python list).</p>
| 1 | 2009-10-22T01:11:46Z | [
"java",
"python",
"garbage-collection"
] |
Why Java and Python garbage collection methods are different? | 21,934 | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| 35 | 2008-08-22T07:35:26Z | 7,826,363 | <p>One big disadvantage of Java's tracing GC is that from time to time it will "stop the world" and freeze the application for a relatively long time to do a full GC. If the heap is big and the the object tree complex, it will freeze for a few seconds. Also each full GC visits the whole object tree over and over again, something that is probably quite inefficient. Another drawback of the way Java does GC is that you have to tell the jvm what heap size you want (if the default is not good enough); the JVM derives from that value several thresholds that will trigger the GC process when there is too much garbage stacking up in the heap.</p>
<p>I presume that this is actually the main cause of the jerky feeling of Android (based on Java), even on the most expensive cellphones, in comparison with the smoothness of iOS (based on ObjectiveC, and using RC). </p>
<p>I'd love to see a jvm option to enable RC memory management, and maybe keeping GC only to run as a last resort when there is no more memory left. </p>
| 2 | 2011-10-19T18:40:07Z | [
"java",
"python",
"garbage-collection"
] |
Why does this python date/time conversion seem wrong? | 21,961 | <pre><code>>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
</code></pre>
<p>time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
| 3 | 2008-08-22T09:06:43Z | 21,973 | <pre><code>mktime(...)
mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch.
</code></pre>
<p>local time... fancy that.</p>
<p>The time tuple:</p>
<pre><code>The other representation is a tuple of 9 integers giving local time.
The tuple items are:
year (four digits, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
</code></pre>
<p>Incidentally, we seem to be 6 hours apart:</p>
<pre><code>>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233356400.0
>>> (1233378000.0 - 1233356400)/(60*60)
6.0
</code></pre>
| 1 | 2008-08-22T09:21:55Z | [
"python",
"datetime"
] |
Why does this python date/time conversion seem wrong? | 21,961 | <pre><code>>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
</code></pre>
<p>time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
| 3 | 2008-08-22T09:06:43Z | 21,974 | <p>Interesting. I don't know, but I did try this:</p>
<pre><code>>>> now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1))
>>> tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1))
>>> tomorrow - now
86400.0
</code></pre>
<p>which is what you expected. My guess? Maybe some time correction was done since the epoch. This could be only a few seconds, something like a leap year. I think I heard something like this before, but can't remember exactly how and when it is done...</p>
| 0 | 2008-08-22T09:22:08Z | [
"python",
"datetime"
] |
Why does this python date/time conversion seem wrong? | 21,961 | <pre><code>>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
</code></pre>
<p>time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
| 3 | 2008-08-22T09:06:43Z | 21,975 | <p>Short answer: Because of timezones.</p>
<p>The Epoch is in UTC.</p>
<p>For example, I'm on IST (Irish Stsandard Time) or GMT+1. time.mktime() is relative to my timezone, so on my system this refers to</p>
<pre><code>>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000.0
</code></pre>
<p>Because you got the result 1233378000, that would suggest that you're 5 hours behind me</p>
<pre><code>>>> (1233378000 - 1233360000) / (60*60)
5
</code></pre>
<p>Have a look at the time.gmtime() function which works off UTC.</p>
| 7 | 2008-08-22T09:24:25Z | [
"python",
"datetime"
] |
Why does this python date/time conversion seem wrong? | 21,961 | <pre><code>>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
</code></pre>
<p>time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
| 3 | 2008-08-22T09:06:43Z | 22,021 | <p>Phil's answer really solved it, but I'll elaborate a little more. Since the epoch is in UTC, if I want to compare other times to the epoch, I need to interpret them as UTC as well.</p>
<pre><code>>>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000
>>> 1233360000 / (60*60*24)
14275
</code></pre>
<p>By converting the time tuple to a timestamp treating is as UTC time, I get a number which <em>is</em> evenly divisible by the number of seconds in a day.</p>
<p>I can use this to convert a date to a days-from-the-epoch representation which is what I'm ultimately after.</p>
| 1 | 2008-08-22T10:12:25Z | [
"python",
"datetime"
] |
How do content discovery engines, like Zemanta and Open Calais work? | 22,059 | <p>I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? </p>
<p>How would a service like Zemanta know what images to suggest to a piece of text for instance? </p>
| 4 | 2008-08-22T10:51:19Z | 23,041 | <p>Open Calais probably use language parsing technology and language statics to guess which words or phrases are Names, Places, Companies, etc. Then, it is just another step to do some kind of search for those entities and return meta data.</p>
<p>Zementa probably does something similar, but matches the phrases against meta-data attached to images in order to acquire related results.</p>
<p>It certainly isn't easy.</p>
| 0 | 2008-08-22T17:58:23Z | [
"python",
"ruby",
"semantics",
"zemanta"
] |
How do content discovery engines, like Zemanta and Open Calais work? | 22,059 | <p>I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? </p>
<p>How would a service like Zemanta know what images to suggest to a piece of text for instance? </p>
| 4 | 2008-08-22T10:51:19Z | 35,667 | <p>I'm not familiar with the specific services listed, but the field of natural language processing has developed a number of techniques that enable this sort of information extraction from general text. As Sean stated, once you have candidate terms, it's not to difficult to search for those terms with some of the other entities in context and then use the results of that search to determine how confident you are that the term extracted is an actual entity of interest.</p>
<p><a href="http://opennlp.sourceforge.net/">OpenNLP</a> is a great project if you'd like to play around with natural language processing. The capabilities you've named would probably be best accomplished with Named Entity Recognizers (NER) (algorithms that locate proper nouns, generally, and sometimes dates as well) and/or Word Sense Disambiguation (WSD) (eg: the word 'bank' has different meanings depending on it's context, and that can be very important when extracting information from text. Given the sentences: "the plane banked left", "the snow bank was high", and "they robbed the bank" you can see how dissambiguation can play an important part in language understanding)</p>
<p>Techniques generally build on each other, and NER is one of the more complex tasks, so to do NER successfully, you will generally need accurate tokenizers (natural language tokenizers, mind you -- statistical approaches tend to fare the best), string stemmers (algorithms that conflate similar words to common roots: so words like informant and informer are treated equally), sentence detection ('Mr. Jones was tall.' is only one sentence, so you can't just check for punctuation), part-of-speech taggers (POS taggers), and WSD.</p>
<p>There is a python port of (parts of) OpenNLP called NLTK (<a href="http://nltk.sourceforge.net">http://nltk.sourceforge.net</a>) but I don't have much experience with it yet. Most of my work has been with the Java and C# ports, which work well. </p>
<p>All of these algorithms are language-specific, of course, and they can take significant time to run (although, it is generally faster than reading the material you are processing). Since the state-of-the-art is largely based on statistical techniques, there is also a considerable error rate to take into account. Furthermore, because the error rate impacts all the stages, and something like NER requires numerous stages of processing, (tokenize -> sentence detect -> POS tag -> WSD -> NER) the error rates compound.</p>
| 7 | 2008-08-30T03:56:57Z | [
"python",
"ruby",
"semantics",
"zemanta"
] |
How do content discovery engines, like Zemanta and Open Calais work? | 22,059 | <p>I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? </p>
<p>How would a service like Zemanta know what images to suggest to a piece of text for instance? </p>
| 4 | 2008-08-22T10:51:19Z | 821,663 | <p>Michal Finkelstein from OpenCalais here.</p>
<p>First, thanks for your interest. I'll reply here but I also encourage you to read more on OpenCalais forums; there's a lot of information there including - but not limited to:
<a href="http://opencalais.com/tagging-information">http://opencalais.com/tagging-information</a>
<a href="http://opencalais.com/how-does-calais-learn">http://opencalais.com/how-does-calais-learn</a>
Also feel free to follow us on Twitter (@OpenCalais) or to email us at team@opencalais.com</p>
<p>Now to the answer:</p>
<p>OpenCalais is based on a decade of research and development in the fields of Natural Language Processing and Text Analytics.</p>
<p>We support the full "NLP Stack" (as we like to call it):
From text tokenization, morphological analysis and POS tagging, to shallow parsing and identifying nominal and verbal phrases.</p>
<p>Semantics come into play when we look for Entities (a.k.a. Entity Extraction, Named Entity Recognition). For that purpose we have a sophisticated rule-based system that combines discovery rules as well as lexicons/dictionaries. This combination allows us to identify names of companies/persons/films, etc., even if they don't exist in any available list.</p>
<p>For the most prominent entities (such as people, companies) we also perform anaphora resolution, cross-reference and name canonization/normalization at the article level, so we'll know that 'John Smith' and 'Mr. Smith', for example, are likely referring to the same person.
So the short answer to your question is - no, it's not just about matching against large databases.</p>
<p>Events/Facts are really interesting because they take our discovery rules one level deeper; we find relations between entities and label them with the appropriate type, for example M&As (relations between two or more companies), Employment Changes (relations between companies and people), and so on. Needless to say, Event/Fact extraction is not possible for systems that are based solely on lexicons.
For the most part, our system is tuned to be precision-oriented, but we always try to keep a reasonable balance between accuracy and entirety.</p>
<p>By the way there are some cool new metadata capabilities coming out later this month so stay tuned.</p>
<p>Regards,</p>
<p>Michal</p>
| 9 | 2009-05-04T19:45:20Z | [
"python",
"ruby",
"semantics",
"zemanta"
] |
Unicode vs UTF-8 confusion in Python / Django? | 22,149 | <p>I stumbled over this passage in the <a href="http://www.djangoproject.com/documentation/tutorial01/">Django tutorial</a>:</p>
<blockquote>
<p>Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.</p>
</blockquote>
<p>Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html">this "Python Unicode Tutorial"</a> which boldly states</p>
<blockquote>
<p>Unicode is a two-byte encoding which covers all of the world's common writing systems.</p>
</blockquote>
<p>which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?</p>
| 25 | 2008-08-22T12:01:53Z | 22,157 | <p>Python stores Unicode as UTF-16. str() will return the UTF-8 representation of the UTF-16 string.</p>
| 0 | 2008-08-22T12:03:47Z | [
"python",
"django",
"unicode"
] |
Unicode vs UTF-8 confusion in Python / Django? | 22,149 | <p>I stumbled over this passage in the <a href="http://www.djangoproject.com/documentation/tutorial01/">Django tutorial</a>:</p>
<blockquote>
<p>Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.</p>
</blockquote>
<p>Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html">this "Python Unicode Tutorial"</a> which boldly states</p>
<blockquote>
<p>Unicode is a two-byte encoding which covers all of the world's common writing systems.</p>
</blockquote>
<p>which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?</p>
| 25 | 2008-08-22T12:01:53Z | 22,168 | <p>From <a href="http://en.wikipedia.org/wiki/UTF-8" rel="nofollow">Wikipedia on UTF-8</a>: </p>
<blockquote>
UTF-8 (8-bit UCS/Unicode Transformation Format) is a <strong>variable-length character encoding for Unicode. It is able to represent any character in the Unicode standard</strong>, yet the initial encoding of byte codes and character assignments for UTF-8 is backwards compatible with ASCII. For these reasons, it is steadily becoming the preferred encoding for e-mail, web pages[1], and other places where characters are stored or streamed.
</blockquote>
<p>So, it's anywhere between one and four bytes depending on which character you wish to represent within the realm of Unicode.</p>
<p><a href="http://en.wikipedia.org/wiki/Unicode" rel="nofollow">From Wikipedia on Unicode:</a></p>
<blockquote>
In computing, Unicode is an industry standard allowing computers to consistently represent and manipulate text expressed in <strong>most of the world's writing systems</strong>.
</blockquote>
<p>So it's able to represent most (but not all) of the world's writing systems. </p>
<p>I hope this helps :)</p>
| -1 | 2008-08-22T12:10:14Z | [
"python",
"django",
"unicode"
] |
Unicode vs UTF-8 confusion in Python / Django? | 22,149 | <p>I stumbled over this passage in the <a href="http://www.djangoproject.com/documentation/tutorial01/">Django tutorial</a>:</p>
<blockquote>
<p>Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.</p>
</blockquote>
<p>Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html">this "Python Unicode Tutorial"</a> which boldly states</p>
<blockquote>
<p>Unicode is a two-byte encoding which covers all of the world's common writing systems.</p>
</blockquote>
<p>which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?</p>
| 25 | 2008-08-22T12:01:53Z | 22,206 | <blockquote>
<p>so what is a "Unicode string" in
Python?</p>
</blockquote>
<p>Python 'knows' that your string is Unicode. Hence if you do regex on it, it will know which is character and which is not etc, which is really helpful. If you did a strlen it will also give the correct result. As an example if you did string count on Hello, you will get 5 (even if it's Unicode). But if you did a string count of a foreign word and that string was not a Unicode string than you will have much larger result. Pythong uses the information form the Unicode Character Database to identify each character in the Unicode String. Hope that helps. </p>
| -2 | 2008-08-22T12:32:04Z | [
"python",
"django",
"unicode"
] |
Unicode vs UTF-8 confusion in Python / Django? | 22,149 | <p>I stumbled over this passage in the <a href="http://www.djangoproject.com/documentation/tutorial01/">Django tutorial</a>:</p>
<blockquote>
<p>Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.</p>
</blockquote>
<p>Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html">this "Python Unicode Tutorial"</a> which boldly states</p>
<blockquote>
<p>Unicode is a two-byte encoding which covers all of the world's common writing systems.</p>
</blockquote>
<p>which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?</p>
| 25 | 2008-08-22T12:01:53Z | 22,208 | <p>Meanwhile, I did a refined research to verify what the internal representation in Python is, and also what its limits are. "<a href="http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python">The Truth About Unicode In Python</a>" is a very good article which cites directly from the Python developers. Apparently, internal representation is either UCS-2 or UCS-4 depending on a compile-time switch. So Jon, it's not UTF-16, but your answer put me on the right track anyway, thanks.</p>
| 8 | 2008-08-22T12:32:59Z | [
"python",
"django",
"unicode"
] |
Unicode vs UTF-8 confusion in Python / Django? | 22,149 | <p>I stumbled over this passage in the <a href="http://www.djangoproject.com/documentation/tutorial01/">Django tutorial</a>:</p>
<blockquote>
<p>Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.</p>
</blockquote>
<p>Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html">this "Python Unicode Tutorial"</a> which boldly states</p>
<blockquote>
<p>Unicode is a two-byte encoding which covers all of the world's common writing systems.</p>
</blockquote>
<p>which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?</p>
| 25 | 2008-08-22T12:01:53Z | 522,827 | <blockquote>
<p>what is a "Unicode string" in Python? Does that mean UCS-2?</p>
</blockquote>
<p>Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (âwide modeâ) for their versions of Python.</p>
<p>You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds.</p>
<blockquote>
<p>plain wrong, or is it?</p>
</blockquote>
<p>Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane).</p>
<p>There is an additional source of confusion stemming from Windows's habit of using the term âUnicodeâ to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit.</p>
| 45 | 2009-02-07T00:54:09Z | [
"python",
"django",
"unicode"
] |
Format numbers to strings in Python | 22,617 | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| 68 | 2008-08-22T15:10:46Z | 22,624 | <p>Formatting in Python is done via the <a href="http://docs.python.org/2/library/stdtypes.html#string-formatting">string formatting (<code>%</code>) operator</a>:</p>
<pre><code>"%02d:%02d:%02d" % (hours, minutes, seconds)
</code></pre>
<p>/Edit: There's also <a href="https://docs.python.org/2/library/time.html#time.strftime">strftime</a>.</p>
| 103 | 2008-08-22T15:12:41Z | [
"python",
"string-formatting"
] |
Format numbers to strings in Python | 22,617 | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| 68 | 2008-08-22T15:10:46Z | 22,630 | <p>You can use C style string formatting:</p>
<pre><code>"%d:%d:d" % (hours, minutes, seconds)
</code></pre>
<p>See here, especially: <a href="https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html" rel="nofollow">https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html</a></p>
| 3 | 2008-08-22T15:13:45Z | [
"python",
"string-formatting"
] |
Format numbers to strings in Python | 22,617 | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| 68 | 2008-08-22T15:10:46Z | 24,962 | <p><em>str()</em> in python on an integer will <strong>not</strong> print any decimal places.</p>
<p>If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).</p>
<p>Perhaps the following code will demonstrate:</p>
<pre><code>>>> str(5)
'5'
>>> int(8.7)
8
</code></pre>
| 0 | 2008-08-24T10:32:49Z | [
"python",
"string-formatting"
] |
Format numbers to strings in Python | 22,617 | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| 68 | 2008-08-22T15:10:46Z | 2,550,630 | <p>Starting in Python 2.6, there is an alternative: the <code>str.format()</code> method. Here are some examples using the existing string format operator (<code>%</code>):</p>
<pre><code>>>> "Name: %s, age: %d" % ('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)
'dec: 45/oct: 055/hex: 0X2D'
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d
'http://xxx.yyy.zzz/user/42.html'
</code></pre>
<p>Here are the equivalent snippets but using <code>str.format()</code>:</p>
<pre><code>>>> "Name: {0}, age: {1}".format('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)
'dec: 45/oct: 0o55/hex: 0X2D'
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d)
'http://xxx.yyy.zzz/user/42.html'
</code></pre>
<p>Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of <a href="http://amzn.com/0132269937">my hardcore Python intro book</a> and the slides for the Intro+Intermediate <a href="http://cyberwebconsulting.com">Python courses I offer</a> from time-to-time. <code>:-)</code></p>
| 74 | 2010-03-31T05:13:20Z | [
"python",
"string-formatting"
] |
Format numbers to strings in Python | 22,617 | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| 68 | 2008-08-22T15:10:46Z | 3,336,493 | <p>If you have a value that includes a decimal, but the decimal value is negligible (ie: 100.0) and try to int that, you will get an error. It seems silly, but calling float first fixes this.</p>
<p>str(int(float([variable])))</p>
| 0 | 2010-07-26T15:46:31Z | [
"python",
"string-formatting"
] |
Format numbers to strings in Python | 22,617 | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| 68 | 2008-08-22T15:10:46Z | 26,250,207 | <p>You can use following to achieve desired functionality</p>
<pre><code>"%d:%d:d" % (hours, minutes, seconds)
</code></pre>
| 1 | 2014-10-08T06:06:44Z | [
"python",
"string-formatting"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 22,682 | <p>In Python 2, use urllib2 which comes with the standard library.</p>
<pre><code>import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
</code></pre>
<p>This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. The documentation can be found <a href="http://docs.python.org/2/library/urllib2.html">here.</a></p>
| 286 | 2008-08-22T15:38:22Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 22,721 | <pre class="lang-py prettyprint-override"><code>import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
output.write(mp3file.read())
</code></pre>
<p>The <code>wb</code> in <code>open('test.mp3','wb')</code> opens a file (and erases any existing file) in binary mode so you can save data with it instead of just text.</p>
| 118 | 2008-08-22T15:58:17Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 22,723 | <p>I agree with Corey, urllib2 is more complete than <a href="http://docs.python.org/lib/module-urllib.html">urllib</a> and should likely be the module used if you want to do more complex things, but to make the answers more complete, urllib is a simpler module if you want just the basics:</p>
<pre><code>import urllib
response = urllib.urlopen('http://www.example.com/sound.mp3')
mp3 = response.read()
</code></pre>
<p>Will work fine. Or, if you don't want to deal with the "response" object you can call <strong>read()</strong> directly:</p>
<pre><code>import urllib
mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()
</code></pre>
| 9 | 2008-08-22T15:58:52Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 22,776 | <p>One more, using <a href="http://docs.python.org/2/library/urllib.html#urllib.urlretrieve"><code>urlretrieve</code></a>:</p>
<pre><code>import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
</code></pre>
<p>(for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve)</p>
<p>Yet another one, with a "progressbar"</p>
<pre><code>import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
</code></pre>
| 759 | 2008-08-22T16:19:09Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 10,744,565 | <p>In 2012, use the <a href="http://docs.python-requests.org/en/latest/index.html">python requests library</a></p>
<pre><code>>>> import requests
>>>
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760
</code></pre>
<p>You can run <code>pip install requests</code> to get it.</p>
<p>Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case.</p>
<hr>
<p>2015-12-30</p>
<p>People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including <code>tqdm</code>:</p>
<pre><code>from tqdm import tqdm
import requests
url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)
with open("10MB", "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
</code></pre>
<p>This is essentially the implementation @kvance described 30 months ago.</p>
| 224 | 2012-05-24T20:08:29Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 16,518,224 | <p>An improved version of the PabloG code for Python 2/3:</p>
<pre><code>from __future__ import ( division, absolute_import, print_function, unicode_literals )
import sys, os, tempfile, logging
if sys.version_info >= (3,):
import urllib.request as urllib2
import urllib.parse as urlparse
else:
import urllib2
import urlparse
def download_file(url, desc=None):
u = urllib2.urlopen(url)
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
filename = os.path.basename(path)
if not filename:
filename = 'downloaded.file'
if desc:
filename = os.path.join(desc, filename)
with open(filename, 'wb') as f:
meta = u.info()
meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
meta_length = meta_func("Content-Length")
file_size = None
if meta_length:
file_size = int(meta_length[0])
print("Downloading: {0} Bytes: {1}".format(url, file_size))
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = "{0:16}".format(file_size_dl)
if file_size:
status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
status += chr(13)
print(status, end="")
print()
return filename
url = "http://download.thinkbroadband.com/10MB.zip"
filename = download_file(url)
print(filename)
</code></pre>
| 14 | 2013-05-13T08:59:44Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 19,011,916 | <p>Wrote <a href="https://pypi.python.org/pypi/wget">wget</a> library in pure Python just for this purpose. It is pumped up <code>urlretrieve</code> with <a href="https://bitbucket.org/techtonik/python-wget/src/6859e7b4aba37cef57616111be890fb59631bc4c/wget.py?at=default#cl-330">these features</a> as of version 2.0.</p>
| 12 | 2013-09-25T17:55:16Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 19,352,848 | <p>This may be a little late, But I saw pabloG's code and couldn't help adding a os.system('cls') to make it look AWESOME! Check it out : </p>
<pre><code> import urllib2,os
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
os.system('cls')
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
</code></pre>
| 2 | 2013-10-14T02:54:01Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 20,218,209 | <p>Source code can be:</p>
<pre><code>import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()
sock.close()
print htmlSource
</code></pre>
| 1 | 2013-11-26T13:21:01Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 21,363,808 | <p>You can get the progress feedback with urlretrieve as well:</p>
<pre><code>def report(blocknr, blocksize, size):
current = blocknr*blocksize
sys.stdout.write("\r{0:.2f}%".format(100.0*current/size))
def downloadFile(url):
print "\n",url
fname = url.split('/')[-1]
print fname
urllib.urlretrieve(url, fname, report)
</code></pre>
| 6 | 2014-01-26T13:12:54Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 29,256,384 | <p>use wget module:</p>
<pre><code>import wget
wget.download('url')
</code></pre>
| 6 | 2015-03-25T12:59:25Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 31,857,152 | <p>Here's how to do it in Python 3 using the standard library:</p>
<ul>
<li><p><a href="https://docs.python.org/3.0/library/urllib.request.html#urllib.request.urlopen"><code>urllib.request.urlopen</code></a></p>
<pre><code>import urllib.request
response = urllib.request.urlopen('http://www.example.com/')
html = response.read()
</code></pre></li>
<li><p><a href="https://docs.python.org/3.0/library/urllib.request.html#urllib.request.urlretrieve"><code>urllib.request.urlretrieve</code></a></p>
<pre><code>import urllib.request
urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
</code></pre></li>
</ul>
| 14 | 2015-08-06T13:30:31Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 33,816,517 | <p>If you have wget installed, you can use parallel_sync.</p>
<p>pip install parallel_sync</p>
<pre><code>from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)
</code></pre>
<p>Doc:
<a href="https://pythonhosted.org/parallel_sync/pages/examples.html" rel="nofollow">https://pythonhosted.org/parallel_sync/pages/examples.html</a></p>
<p>This is pretty powerful. It can download files in parallel, retry upon failure , and it can even download files on a remote machine.</p>
| 2 | 2015-11-19T23:48:06Z | [
"python"
] |
How do I download a file over HTTP using Python? | 22,676 | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| 492 | 2008-08-22T15:34:13Z | 39,573,536 | <p>Following are the most commonly used calls for downloading files in python:</p>
<ol>
<li><p><code>urllib.urlretrieve ('url_to_file', file_name)</code></p></li>
<li><p><code>urllib2.urlopen('url_to_file')</code></p></li>
<li><p><code>requests.get(url)</code></p></li>
<li><p><code>wget.download('url', file_name)</code></p></li>
</ol>
<p>Note: <code>urlopen</code> and <code>urlretrieve</code> are found to perform relatively bad with downloading large files (size > 500 MB). <code>requests.get</code> stores the file in-memory until download is complete. </p>
| 2 | 2016-09-19T12:45:10Z | [
"python"
] |
What's the best way to duplicate fork() in windows? | 23,397 | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| 20 | 2008-08-22T20:27:46Z | 23,414 | <p>Possibly a version of spawn() for python? <a href="http://en.wikipedia.org/wiki/Spawn_(operating_system)" rel="nofollow">http://en.wikipedia.org/wiki/Spawn_(operating_system)</a></p>
| 0 | 2008-08-22T20:34:00Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] |
What's the best way to duplicate fork() in windows? | 23,397 | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| 20 | 2008-08-22T20:27:46Z | 23,422 | <p>Have a look at the process management functions in the <a href="http://python.org/doc/2.5/lib/os-process.html" rel="nofollow">os module</a>. There are function for starting new processes in many different ways, both synchronously and asynchronously.</p>
<p>I should note also that Windows doesn't provide functionality that is exactly like fork() on other systems. To do multiprocessing on Windows, you will need to use the <a href="http://python.org/doc/2.5/lib/module-threading.html" rel="nofollow">threading</a> module.</p>
| 4 | 2008-08-22T20:38:18Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] |
What's the best way to duplicate fork() in windows? | 23,397 | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| 20 | 2008-08-22T20:27:46Z | 23,510 | <p>In addition to the process management code in the os module that Greg pointed out, you should also take a look at the threading module: <a href="https://docs.python.org/library/threading.html" rel="nofollow">https://docs.python.org/library/threading.html</a></p>
<pre><code>from threading import Thread
def separate_computations(x, y):
print sum(x for i in range(y)) # really expensive multiplication
Thread(target=separate_compuations, args=[57, 83]).start()
print "I'm continuing while that other function runs in another thread!"
</code></pre>
| 3 | 2008-08-22T21:16:07Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] |
What's the best way to duplicate fork() in windows? | 23,397 | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| 20 | 2008-08-22T20:27:46Z | 25,117 | <p>You might also like using the processing module (<a href="http://pypi.python.org/pypi/processing" rel="nofollow">http://pypi.python.org/pypi/processing</a>). It has lot's of functionality for writing parallel systems with the same API as the threading module...</p>
| 2 | 2008-08-24T15:38:21Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] |
What's the best way to duplicate fork() in windows? | 23,397 | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| 20 | 2008-08-22T20:27:46Z | 52,191 | <p>The Threading example from Eli will run the thread, but not do any of the work after that line. </p>
<p>I'm going to look into the processing module and the subprocess module. I think the com method I'm running needs to be in another process, not just in another thread.</p>
| 2 | 2008-09-09T15:37:18Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] |
What's the best way to duplicate fork() in windows? | 23,397 | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| 20 | 2008-08-22T20:27:46Z | 170,387 | <p><code>fork()</code> <em>has</em> in fact been duplicated in Windows, under <a href="https://en.wikipedia.org/wiki/Cygwin" rel="nofollow">Cygwin</a>, but it's pretty hairy.</p>
<blockquote>
<p>The fork call in Cygwin is particularly interesting because it does not map well on top of the Win32 API. This makes it very difficult to implement correctly.</p>
</blockquote>
<p>See the <a href="http://cygwin.com/cygwin-ug-net/highlights.html#ov-hi-process" rel="nofollow">The Cygwin User's Guide</a> for a description of this hack.</p>
| 10 | 2008-10-04T14:10:36Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] |
What's the best way to duplicate fork() in windows? | 23,397 | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| 20 | 2008-08-22T20:27:46Z | 6,020,663 | <p>Use the python <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing module</a> which will work everywhere.</p>
<p>Here is a <a href="http://www.ibm.com/developerworks/aix/library/au-multiprocessing/">IBM developerWords article</a> that shows how to convert from os.fork() to the multiprocessing module.</p>
| 15 | 2011-05-16T16:51:18Z | [
"python",
"windows",
"process",
"subprocess",
"fork"
] |
How can I graph the Lines of Code history for git repo? | 23,907 | <p>Basically I want to get the number of lines-of-code in the repository after each commit.</p>
<p>The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *", and a script that run git reset --hard on each commit, then ran wc -l</p>
<p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example):</p>
<pre><code>me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
</code></pre>
<p>I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example)</p>
<pre><code>require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
</code></pre>
| 34 | 2008-08-23T03:00:46Z | 24,190 | <p>The first thing that jumps to mind is the possibility of your git history having a nonlinear history. You might have difficulty determining a sensible sequence of commits.</p>
<p>Having said that, it seems like you could keep a log of commit ids and the corresponding lines of code in that commit. In a post-commit hook, starting from the HEAD revision, work backwards (branching to multiple parents if necessary) until all paths reach a commit that you've already seen before. That should give you the total lines of code for each commit id.</p>
<p>Does that help any? I have a feeling that I've misunderstood something about your question.</p>
| 4 | 2008-08-23T12:39:52Z | [
"python",
"ruby",
"git",
"lines-of-code",
"sloc"
] |
How can I graph the Lines of Code history for git repo? | 23,907 | <p>Basically I want to get the number of lines-of-code in the repository after each commit.</p>
<p>The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *", and a script that run git reset --hard on each commit, then ran wc -l</p>
<p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example):</p>
<pre><code>me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
</code></pre>
<p>I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example)</p>
<pre><code>require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
</code></pre>
| 34 | 2008-08-23T03:00:46Z | 35,664 | <p>You may get both added and removed lines with git log, like:</p>
<pre><code>git log --shortstat --reverse --pretty=oneline
</code></pre>
<p>From this, you can write a similar script to the one you did using this info. In python:</p>
<pre><code>#!/usr/bin/python
"""
Display the per-commit size of the current git branch.
"""
import subprocess
import re
import sys
def main(argv):
git = subprocess.Popen(["git", "log", "--shortstat", "--reverse",
"--pretty=oneline"], stdout=subprocess.PIPE)
out, err = git.communicate()
total_files, total_insertions, total_deletions = 0, 0, 0
for line in out.split('\n'):
if not line: continue
if line[0] != ' ':
# This is a description line
hash, desc = line.split(" ", 1)
else:
# This is a stat line
data = re.findall(
' (\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(-\)',
line)
files, insertions, deletions = ( int(x) for x in data[0] )
total_files += files
total_insertions += insertions
total_deletions += deletions
print "%s: %d files, %d lines" % (hash, total_files,
total_insertions - total_deletions)
if __name__ == '__main__':
sys.exit(main(sys.argv))
</code></pre>
| 22 | 2008-08-30T03:55:23Z | [
"python",
"ruby",
"git",
"lines-of-code",
"sloc"
] |
How can I graph the Lines of Code history for git repo? | 23,907 | <p>Basically I want to get the number of lines-of-code in the repository after each commit.</p>
<p>The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *", and a script that run git reset --hard on each commit, then ran wc -l</p>
<p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example):</p>
<pre><code>me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
</code></pre>
<p>I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example)</p>
<pre><code>require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
</code></pre>
| 34 | 2008-08-23T03:00:46Z | 2,854,506 | <p>You might also consider <a href="http://gitstats.sourceforge.net/">gitstats</a>, which generates this graph as an html file. </p>
| 22 | 2010-05-18T04:09:01Z | [
"python",
"ruby",
"git",
"lines-of-code",
"sloc"
] |
How can I graph the Lines of Code history for git repo? | 23,907 | <p>Basically I want to get the number of lines-of-code in the repository after each commit.</p>
<p>The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *", and a script that run git reset --hard on each commit, then ran wc -l</p>
<p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example):</p>
<pre><code>me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
</code></pre>
<p>I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example)</p>
<pre><code>require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
</code></pre>
| 34 | 2008-08-23T03:00:46Z | 3,180,919 | <p><a href="http://github.com/ITikhonov/git-loc">http://github.com/ITikhonov/git-loc</a> worked right out of the box for me.</p>
| 9 | 2010-07-05T16:18:32Z | [
"python",
"ruby",
"git",
"lines-of-code",
"sloc"
] |
Python code generator for Visual Studio? | 24,193 | <p>I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.</p>
<p>Does anyone know if such a custom generator for Visual Studio 2008 exists?</p>
| 3 | 2008-08-23T12:41:43Z | 24,199 | <p>I recall that in previous versions of VS, there was a way to add custom build steps to the build process. I used that a lot to do exactly the kind of automated code generation you describe.</p>
<p>I imagine the custom build step feature is still there in 2008.</p>
| 2 | 2008-08-23T12:49:12Z | [
"python",
"visual-studio-2008",
"code-generation"
] |
Python code generator for Visual Studio? | 24,193 | <p>I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.</p>
<p>Does anyone know if such a custom generator for Visual Studio 2008 exists?</p>
| 3 | 2008-08-23T12:41:43Z | 24,236 | <p>I don't understand what you are trying to do here. Are you trying to execute a Python script that generates a C# file and then compile that with the project? Or are you trying to compile a Python script to C#?</p>
| 1 | 2008-08-23T13:42:39Z | [
"python",
"visual-studio-2008",
"code-generation"
] |
Python code generator for Visual Studio? | 24,193 | <p>I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.</p>
<p>Does anyone know if such a custom generator for Visual Studio 2008 exists?</p>
| 3 | 2008-08-23T12:41:43Z | 24,248 | <p>OK, I see. Well, as far as I know there isn't any code generator for Python. There is a good introduction on how to roll your own <a href="http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/" rel="nofollow">here</a>.</p>
<p>Actually, that's quite an under-used part of the environment, I suppose it's so because it needs you to use the IDE to compile the project, as it'd seem only the IDE knows about these "generators", but MSBuild ignores them.</p>
| 1 | 2008-08-23T14:07:27Z | [
"python",
"visual-studio-2008",
"code-generation"
] |
Python code generator for Visual Studio? | 24,193 | <p>I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.</p>
<p>Does anyone know if such a custom generator for Visual Studio 2008 exists?</p>
| 3 | 2008-08-23T12:41:43Z | 222,427 | <p>I think <a href="http://nedbatchelder.com/code/cog/" rel="nofollow">Cog</a> does what you want.</p>
| 3 | 2008-10-21T16:03:42Z | [
"python",
"visual-studio-2008",
"code-generation"
] |
Python code generator for Visual Studio? | 24,193 | <p>I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.</p>
<p>Does anyone know if such a custom generator for Visual Studio 2008 exists?</p>
| 3 | 2008-08-23T12:41:43Z | 223,387 | <p>I dug through my old bookmarks (I love Del.icio.us!) and found this article: <a href="http://blogs.acceleration.net/ryan/articles/577.aspx" rel="nofollow">Code Generation with Python, Cog, and Nant</a>. Keep in mind that anything you can do in NAnt can probably be done in MSBuild as well. This should be enough to get you started.</p>
| 1 | 2008-10-21T20:30:33Z | [
"python",
"visual-studio-2008",
"code-generation"
] |
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | 24,931 | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| 7 | 2008-08-24T08:46:57Z | 24,939 | <p>In which context are you asking?</p>
<p>Are you trying to capture the output from a program you start on the command line?</p>
<p>if so, then this is how to execute it:</p>
<pre><code>somescript.py | your-capture-program-here
</code></pre>
<p>and to read the output, just read from standard input.</p>
<p>If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.</p>
| 0 | 2008-08-24T09:05:20Z | [
"python",
"windows",
"cmd"
] |
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | 24,931 | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| 7 | 2008-08-24T08:46:57Z | 24,942 | <p>You want <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess</a>. Look specifically at Popen in 17.1.1 and communicate in 17.1.2.</p>
| 1 | 2008-08-24T09:27:54Z | [
"python",
"windows",
"cmd"
] |
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | 24,931 | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| 7 | 2008-08-24T08:46:57Z | 24,949 | <p>If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p>
<pre><code>python script_a.py | python script_b.py
</code></pre>
<p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href="http://en.wikipedia.org/wiki/Standard_streams" rel="nofollow">standard streams</a> on Wikipedia.</p>
<p>If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p>
<pre><code>import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
</code></pre>
<p>See the Python <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href="http://docs.python.org/lib/bltin-file-objects.html" rel="nofollow">file objects</a>.</p>
<p>For use with pipes, reading from standard input as <a href="http://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939" rel="nofollow">lassevk</a> suggested you'd do something like this:</p>
<pre><code>import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
</code></pre>
<p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href="http://docs.python.org/lib/module-sys.html" rel="nofollow">sys</a> module. You might also want to take a look at the <a href="http://docs.python.org/lib/module-pipes.html" rel="nofollow">pipes</a> module.</p>
<p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href="http://docs.python.org/lib/poll-objects.html" rel="nofollow">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>
| 9 | 2008-08-24T09:39:08Z | [
"python",
"windows",
"cmd"
] |
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | 24,931 | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| 7 | 2008-08-24T08:46:57Z | 29,169 | <p>Actually, you definitely can, and it's beautiful, ugly, and crazy at the same time!</p>
<p>You can replace sys.stdout and sys.stderr with StringIO objects that collect the output.</p>
<p>Here's an example, save it as evil.py:</p>
<pre><code>import sys
import StringIO
s = StringIO.StringIO()
sys.stdout = s
print "hey, this isn't going to stdout at all!"
print "where is it ?"
sys.stderr.write('It actually went to a StringIO object, I will show you now:\n')
sys.stderr.write(s.getvalue())
</code></pre>
<p>When you run this program, you will see that:</p>
<ul>
<li>nothing went to stdout (where print usually prints to)</li>
<li>the first string that gets written to stderr is the one starting with 'It'</li>
<li>the next two lines are the ones that were collected in the StringIO object</li>
</ul>
<p>Replacing sys.stdout/err like this is an application of what's called monkeypatching. Opinions may vary whether or not this is 'supported', and it is definitely an ugly hack, but it has saved my bacon when trying to wrap around external stuff once or twice.</p>
<p>Tested on Linux, not on Windows, but it should work just as well. Let me know if it works on Windows!</p>
| 3 | 2008-08-26T23:16:16Z | [
"python",
"windows",
"cmd"
] |
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | 24,931 | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| 7 | 2008-08-24T08:46:57Z | 3,378,965 | <p>I think I can point you to a good answer for the first part of your question. </p>
<blockquote>
<p><em>1. Is it possible to capture Python interpreter's output from a Python
script?</em></p>
</blockquote>
<p>The answer is "<em>yes</em>", and personally I like the following lifted from the examples in the <em><a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">PEP 343 -- The "with" Statement</a></em> document.</p>
<pre><code>from contextlib import contextmanager
import sys
@contextmanager
def stdout_redirected(new_stdout):
saved_stdout = sys.stdout
sys.stdout = new_stdout
try:
yield None
finally:
sys.stdout.close()
sys.stdout = saved_stdout
</code></pre>
<p>And used like this:</p>
<pre><code>with stdout_redirected(open("filename.txt", "w")):
print "Hello world"
</code></pre>
<p>A nice aspect of it is that it can be applied selectively around just a portion of a script's execution, rather than its entire extent, and stays in effect even when unhandled exceptions are raised within its context. If you re-open the file in append-mode after its first use, you can accumulate the results into a single file:</p>
<pre><code>with stdout_redirected(open("filename.txt", "w")):
print "Hello world"
print "screen only output again"
with stdout_redirected(open("filename.txt", "a")):
print "Hello world2"
</code></pre>
<p>Of course, the above be also be extended to also redirect <code>sys.stderr</code> to the same or another file. Also see this <a href="http://stackoverflow.com/a/16571630/355230">answer</a> to a related question.</p>
| 4 | 2010-07-31T16:40:30Z | [
"python",
"windows",
"cmd"
] |
Binary buffer in Python | 25,116 | <p>In Python you can use <a href="https://docs.python.org/library/struct.html">StringIO</a> for a file-like buffer for character data. <a href="https://docs.python.org/library/mmap.html">Memory-mapped file</a> basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html">ByteArrayOutputStream</a>?</p>
<p>The use-case I have is I want to create a ZIP file in memory, and <a href="https://docs.python.org/library/zipfile.html">ZipFile</a> requires a file-like object.</p>
| 41 | 2008-08-24T15:37:50Z | 25,123 | <p>Look at the struct package: <a href="https://docs.python.org/library/struct.html" rel="nofollow">https://docs.python.org/library/struct.html</a>, it allows you to interpret strings as packed binary data.</p>
<p>Not sure if this will completely answer your question but you can use struct.unpack() to convert binary data to python objects.</p>
<pre>
<code>
import struct
f = open(filename, "rb")
s = f.read(8)
x, y = struct.unpack(">hl", s)
</code>
</pre>
<p>int this example, the ">" tells to read big-endian the "h" reads a 2-byte short, and the "l" is for a 4-byte long. you can obviously change these to whatever you need to read out of the binary data...</p>
| 3 | 2008-08-24T15:50:54Z | [
"python",
"binary",
"io",
"buffer"
] |
Binary buffer in Python | 25,116 | <p>In Python you can use <a href="https://docs.python.org/library/struct.html">StringIO</a> for a file-like buffer for character data. <a href="https://docs.python.org/library/mmap.html">Memory-mapped file</a> basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html">ByteArrayOutputStream</a>?</p>
<p>The use-case I have is I want to create a ZIP file in memory, and <a href="https://docs.python.org/library/zipfile.html">ZipFile</a> requires a file-like object.</p>
| 41 | 2008-08-24T15:37:50Z | 25,180 | <p>As long as you don't try to put any unicode data into your <code>StringIO</code> and you are careful NOT to use <code>cStringIO</code> you should be fine.</p>
<p>According to the <a href="https://docs.python.org/library/stringio.html" rel="nofollow">StringIO</a> documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, <code>StringIO</code> does something special when someone does a <code>f.write(u"asdf")</code> (which ZipFile does not do, to my knowledge). Anyway;</p>
<pre><code>import zipfile
import StringIO
s = StringIO.StringIO()
z = zipfile.ZipFile(s, "w")
z.write("test.txt")
z.close()
f = file("x.zip", "w")
f.write(s.getvalue())
s.close()
f.close()
</code></pre>
<p>works just as expected, and there's no difference between the file in the resulting archive and the original file.</p>
<p>If you know of a particular case where this approach does not work, I'd be most interested to hear about it :)</p>
| 24 | 2008-08-24T16:52:29Z | [
"python",
"binary",
"io",
"buffer"
] |
Binary buffer in Python | 25,116 | <p>In Python you can use <a href="https://docs.python.org/library/struct.html">StringIO</a> for a file-like buffer for character data. <a href="https://docs.python.org/library/mmap.html">Memory-mapped file</a> basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html">ByteArrayOutputStream</a>?</p>
<p>The use-case I have is I want to create a ZIP file in memory, and <a href="https://docs.python.org/library/zipfile.html">ZipFile</a> requires a file-like object.</p>
| 41 | 2008-08-24T15:37:50Z | 7,357,938 | <p>You are probably looking for <a href="http://docs.python.org/release/3.1.3/library/io.html#binary-i-o">io.BytesIO</a> class. It works exactly like StringIO except that it supports binary data:</p>
<pre><code>from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")
</code></pre>
<p>StringIO will throw TypeError:</p>
<pre><code>from io import StringIO
sio = StringIO(b"some initial binary data: \x00\x01")
</code></pre>
| 55 | 2011-09-09T06:34:34Z | [
"python",
"binary",
"io",
"buffer"
] |
pyGame within a pyGTK application | 25,661 | <p>What is the best way to use PyGame (SDL) within a PyGTK application?</p>
<p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
| 7 | 2008-08-25T04:36:48Z | 25,761 | <p>You may be interested in <a href="http://www.daa.com.au/pipermail/pygtk/2006-September/012888.html" rel="nofollow">this message thread</a>. Looks like they recommend against it.</p>
| 1 | 2008-08-25T08:08:46Z | [
"python",
"gtk",
"pygtk",
"sdl",
"pygame"
] |
pyGame within a pyGTK application | 25,661 | <p>What is the best way to use PyGame (SDL) within a PyGTK application?</p>
<p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
| 7 | 2008-08-25T04:36:48Z | 28,935 | <p>I've never attempted it myself, but hearing plenty about other people who've tried, it's not a road you want to go down.</p>
<p>There is the alternative of putting the gui in pygame itself. There are plenty of gui toolkits built specifically for pygame that you could use. Most of them are rather unfinished, but there are 2 big, actively maintained ones: <a href="http://www.pygame.org/project/108/" rel="nofollow">PGU</a> and <a href="http://www.pygame.org/project/125/" rel="nofollow">OcempGUI</a>. The full list on the pygame site is <a href="http://www.pygame.org/tags/gui" rel="nofollow">here</a>.</p>
| 7 | 2008-08-26T19:36:24Z | [
"python",
"gtk",
"pygtk",
"sdl",
"pygame"
] |
pyGame within a pyGTK application | 25,661 | <p>What is the best way to use PyGame (SDL) within a PyGTK application?</p>
<p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
| 7 | 2008-08-25T04:36:48Z | 31,950 | <p>PyGame works much better when it can manage its own window, or even better, use the whole screen. GTK has flexible enough widgets to allow creation of a drawing area. </p>
<p><a href="http://faq.pygtk.org/index.py?req=show&file=faq23.042.htp" rel="nofollow">This page</a> may help, though, if you want to try it.</p>
| 1 | 2008-08-28T10:04:23Z | [
"python",
"gtk",
"pygtk",
"sdl",
"pygame"
] |