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
In Python, how can I efficiently manage references between script files?
287,845
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p> <p>Currently, I have this:</p> <pre><code>import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar </code></pre> <p>My preference would be the following:</p> <pre><code>import Foo import Bar </code></pre> <p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p> <p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
6
2008-11-13T18:49:03Z
288,908
<p>The simplest way is to set (or add to) PYTHONPATH, and put (or symlink) your modules and packages into a path contained in PYTHONPATH.</p>
1
2008-11-14T00:43:32Z
[ "python", "scripting", "metadata" ]
In Python, how can I efficiently manage references between script files?
287,845
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p> <p>Currently, I have this:</p> <pre><code>import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar </code></pre> <p>My preference would be the following:</p> <pre><code>import Foo import Bar </code></pre> <p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p> <p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
6
2008-11-13T18:49:03Z
288,944
<p>My solution was to package up one utility that would import the module: my_util is in site packages</p> <pre><code>import my_util foo = myutil.import_script('..//shared1//reusable_foo') if foo == None: sys.exit(1) def import_script(script_path, log_status = True): """ imports a module and returns the handle """ lpath = os.path.split(script_path) if lpath[1] == '': log('Error in script "%s" in import_script' % (script_path)) return None #check if path is already in sys.path so we don't repeat npath = None if lpath[0] == '': npath = '.' else: if lpath[0] not in sys.path: npath = lpath[0] if npath != None: try: sys.path.append(npath) except: if log_status == True: log('Error adding path "%s" in import_script' % npath) return None try: mod = __import__(lpath[1]) except: error_trace,error_reason = FormatExceptionInfo() if log_status == True: log('Error importing "%s" module in import_script: %s' % (script_path, error_trace + error_reason)) sys.path.remove(npath) return None return mod </code></pre>
0
2008-11-14T01:08:06Z
[ "python", "scripting", "metadata" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
287,896
<p>For Windows you cannot print to console with colors unless you're using the win32api.</p> <p>For Linux it's as simple as using print, with the escape sequences outlined here:</p> <p><a href="http://www.linuxhowtos.org/Tips%20and%20Tricks/ansi_escape_sequences.htm">Colors</a></p> <p>For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:</p> <pre><code># </code></pre>
15
2008-11-13T19:06:23Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
287,919
<p>You can use the Python implementation of the curses library: <a href="http://docs.python.org/library/curses.html">http://docs.python.org/library/curses.html</a></p> <p>Also, run this and you'll find your box:</p> <pre><code>for i in range(255): print i, chr(i) </code></pre>
12
2008-11-13T19:13:59Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
287,934
<p>You want to learn about ANSI escape sequences. Here's a brief example:</p> <pre><code>CSI="\x1B[" reset=CSI+"m" print CSI+"31;40m" + "Colored Text" + CSI + "0m" </code></pre> <p>For more info see <a href="http://en.wikipedia.org/wiki/ANSI_escape_code">http://en.wikipedia.org/wiki/ANSI_escape_code</a></p> <p>For a block character, try a unicode character like \u2588:</p> <pre><code>print u"\u2588" </code></pre> <p>Putting it all together:</p> <pre><code>print CSI+"31;40m" + u"\u2588" + CSI + "0m" </code></pre>
53
2008-11-13T19:22:54Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
287,944
<p>This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some python code from the <a href="https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py">blender build scripts</a>:</p> <pre><code>class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' </code></pre> <p>To use code like this, you can do something like </p> <pre><code>print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC </code></pre> <p>This will work on unixes including OS X, linux and windows (provided you use <a href="https://github.com/adoxa/ansicon">ANSICON</a>, or in Windows 10 provided you enable <a href="https://msdn.microsoft.com/en-us/library/mt638032">VT100 emulation</a>). There are ansi codes for setting the color, moving the cursor, and more.</p> <p>If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The <a href="http://docs.python.org/howto/curses.html">Python Curses HowTO</a> is a good introduction.</p> <p>If you are not using extended ASCII (i.e. not on a PC), you are stuck with the ascii characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM <a href="http://telecom.tbi.net/asc-ibm.html">extended ascii character set</a>, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".</p> <p>Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the <a href="http://dwarffortresswiki.org/DF2014:Tilesets">Dwarf Fortress Wiki</a> see (<a href="http://dwarffortresswiki.org/Tileset_repository">user-made tilesets</a>).</p> <p>The <a href="http://en.wikipedia.org/wiki/TMDC">Text Mode Demo Contest</a> has more resources for doing graphics in text mode.</p> <p>Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!</p>
878
2008-11-13T19:25:07Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
287,987
<p>If you are programming a game perhaps you would like to change the background color and use only spaces? For example:</p> <pre><code>print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m" </code></pre>
10
2008-11-13T19:38:57Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
288,030
<h2>For the characters</h2> <p>Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.</p> <p>Try the following:</p> <pre><code>import unicodedata fp= open("character_list", "w") for index in xrange(65536): char= unichr(index) try: its_name= unicodedata.name(char) except ValueError: its_name= "N/A" fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name) fp.close() </code></pre> <p>Examine the file later with your favourite viewer.</p> <h2>For the colors</h2> <p><a href="http://www.python.org/doc/2.5.2/lib/module-curses.html" rel="nofollow">curses</a> is the module you want to use. Check this <a href="http://docs.python.org/howto/curses.html" rel="nofollow">tutorial</a>.</p>
2
2008-11-13T19:53:03Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
288,556
<p>On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.</p> <p>To see complete code that supports both ways, see the <a href="http://code.google.com/p/testoob/source/browse/trunk/src/testoob/reporting/colored.py">color console reporting code</a> from <a href="http://www.testoob.org">Testoob</a>.</p> <p>ctypes example:</p> <pre><code>import ctypes # Constants from the Windows API STD_OUTPUT_HANDLE = -11 FOREGROUND_RED = 0x0004 # text color contains red. def get_csbi_attributes(handle): # Based on IPython's winconsole.py, written by Alexander Belchenko import struct csbi = ctypes.create_string_buffer(22) res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) assert res (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) return wattr handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) reset = get_csbi_attributes(handle) ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED) print "Cherry on top" ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset) </code></pre>
21
2008-11-13T22:22:30Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
291,431
<p>There's also a module called WConIO that does much the same thing. Unfortunately the author will probably not be able to build a Python 2.6 version any time soon.</p>
0
2008-11-14T21:07:53Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
293,633
<p>I'm surprised no one has mentioned the <a href="http://pypi.python.org/pypi/termcolor">Python termcolor module</a>. Usage is pretty simple:</p> <pre><code>from termcolor import colored print colored('hello', 'red'), colored('world', 'green') </code></pre> <p>It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...</p>
409
2008-11-16T07:31:39Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
1,073,959
<p>Here's a curses example:</p> <pre><code>import curses def main(stdscr): stdscr.clear() if curses.has_colors(): for i in xrange(1, curses.COLORS): curses.init_pair(i, i, curses.COLOR_BLACK) stdscr.addstr("COLOR %d! " % i, curses.color_pair(i)) stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD) stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT) stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE) stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK) stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM) stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE) stdscr.refresh() stdscr.getch() if __name__ == '__main__': print "init..." curses.wrapper(main) </code></pre>
9
2009-07-02T11:59:17Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
3,332,860
<p>The answer is <a href="http://pypi.python.org/pypi/colorama">Colorama</a> for all cross-platform coloring in Python.</p>
281
2010-07-26T07:07:14Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
7,839,185
<p>I wrote a simple module, available at: <a href="http://pypi.python.org/pypi/colorconsole" rel="nofollow">http://pypi.python.org/pypi/colorconsole</a></p> <p>It works with Windows, Mac OS X and Linux. It uses ANSI for Linux and Mac, but native calls to console functions on Windows. You have colors, cursor positioning and keyboard input. It is not a replacement for curses, but can be very useful if you need to use in simple scripts or ASCII games.</p>
2
2011-10-20T16:34:37Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
8,548,994
<p>My favorite way is with the <a href="http://pypi.python.org/pypi/blessings/">Blessings</a> library (full disclosure: I wrote it). For example:</p> <pre><code>from blessings import Terminal t = Terminal() print t.red('This is red.') print t.bold_bright_red_on_black('Bright red on black') </code></pre> <p>To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in <a href="http://pypi.python.org/pypi/nose-progressive/">nose-progressive</a>:</p> <pre><code>print t.on_green(' ') </code></pre> <p>You can print in specific locations as well:</p> <pre><code>with t.location(0, 5): print t.on_yellow(' ') </code></pre> <p>If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:</p> <pre><code>print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t) </code></pre> <p>The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!</p>
51
2011-12-18T00:32:49Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
8,774,709
<p>You could use <a href="http://www.nicosphere.net/clint-command-line-library-for-python/">CLINT</a>:</p> <pre><code>from clint.textui import colored print colored.red('some warning message') print colored.green('nicely done!') </code></pre> <p><a href="https://github.com/kennethreitz/clint">Get it from GitHub</a>.</p>
11
2012-01-08T01:40:35Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
11,178,541
<p>To address this problem I created a mind-numbingly simple package to print strings with interpolated color codes, called <a href="https://github.com/brianmhunt/icolor" rel="nofollow">icolor</a>.</p> <p>icolor includes two functions: <code>cformat</code> and <code>cprint</code>, each of which takes a string with substrings that are interpolated to map to ANSI escape sequences e.g.</p> <pre><code>from icolor import cformat # there is also cprint cformat("This is #RED;a red string, partially with a #xBLUE;blue background") 'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m' </code></pre> <p>All the ANSI colors are included (e.g. <code>#RED;</code>, <code>#BLUE;</code>, etc.), as well as <code>#RESET;</code>, <code>#BOLD;</code> and others.</p> <p>Background colors have an <code>x</code> prefix, so a green background would be <code>#xGREEN;</code>.</p> <p>One can escape <code>#</code> with <code>##</code>.</p> <p>Given its simplicity, the best documentation is probably <a href="https://github.com/brianmhunt/icolor/blob/master/icolor.py" rel="nofollow">the code itself</a>.</p> <p>It is <a href="http://pypi.python.org/pypi/icolor/1.0" rel="nofollow">on PYPI</a>, so one can <code>sudo easy_install icolor</code>.</p>
0
2012-06-24T15:07:49Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
11,193,790
<p>If you are using Windows, then here you go!</p> <pre><code># display text on a Windows console # Windows XP with Python27 or Python32 from ctypes import windll # needed for Python2/Python3 diff try: input = raw_input except: pass STD_OUTPUT_HANDLE = -11 stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) # look at the output and select the color you want # for instance hex E is yellow on black # hex 1E is yellow on blue # hex 2E is yellow on green and so on for color in range(0, 75): windll.kernel32.SetConsoleTextAttribute(stdout_handle, color) print("%X --&gt; %s" % (color, "Have a fine day!")) input("Press Enter to go on ... ") </code></pre>
7
2012-06-25T16:59:39Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
11,278,750
<p>note how well the <code>with</code> keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):</p> <pre><code>from colorama import Fore, Style import sys class Highlight: def __init__(self, clazz, color): self.color = color self.clazz = clazz def __enter__(self): print(self.color, end="") def __exit__(self, type, value, traceback): if self.clazz == Fore: print(Fore.RESET, end="") else: assert self.clazz == Style print(Style.RESET_ALL, end="") sys.stdout.flush() with Highlight(Fore, Fore.GREEN): print("this is highlighted") print("this is not") </code></pre>
13
2012-07-01T00:41:40Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
15,647,557
<p><a href="https://raw.github.com/fabric/fabric/master/fabric/colors.py">https://raw.github.com/fabric/fabric/master/fabric/colors.py</a></p> <pre><code>""" .. versionadded:: 0.9.2 Functions for wrapping strings in ANSI color codes. Each function within this module returns the input string ``text``, wrapped with ANSI color codes for the appropriate color. For example, to print some text as green on supporting terminals:: from fabric.colors import green print(green("This text is green!")) Because these functions simply return modified strings, you can nest them:: from fabric.colors import red, green print(red("This sentence is red, except for " + \ green("these words, which are green") + ".")) If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on for that particular invocation, which usually shows up as a bold or brighter version of the original color on most terminals. """ def _wrap_with(code): def inner(text, bold=False): c = code if bold: c = "1;%s" % c return "\033[%sm%s\033[0m" % (c, text) return inner red = _wrap_with('31') green = _wrap_with('32') yellow = _wrap_with('33') blue = _wrap_with('34') magenta = _wrap_with('35') cyan = _wrap_with('36') white = _wrap_with('37') </code></pre>
8
2013-03-26T21:15:20Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
17,064,509
<p>I have wrapped @joeld answer into a module with global functions that I can use anywhere in my code.</p> <p>file: log.py </p> <pre><code>HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = "\033[1m" def disable(): HEADER = '' OKBLUE = '' OKGREEN = '' WARNING = '' FAIL = '' ENDC = '' def infog( msg): print OKGREEN + msg + ENDC def info( msg): print OKBLUE + msg + ENDC def warn( msg): print WARNING + msg + ENDC def err( msg): print FAIL + msg + ENDC </code></pre> <p>use as follows:</p> <pre><code> import log log.info("Hello World") log.err("System Error") </code></pre>
18
2013-06-12T11:38:01Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
18,786,263
<p>I use the colorama module for coloured terminal printing in Python. A link is here <a href="http://pypi.python.org/pypi/colorama">http://pypi.python.org/pypi/colorama</a></p> <p>Some example code of printing red and green text:</p> <pre><code>from colorama import * print(Fore.GREEN + 'Green text') print(Fore.RED + 'Red text') </code></pre> <p>I used colorama to write a basic Matrix program</p> <p>Installation on Ubuntu (your distribution install command may be different)</p> <pre><code>sudo apt-get install python-pip sudo pip install colorama </code></pre>
16
2013-09-13T12:24:50Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
18,923,126
<p>My two cents (<a href="https://github.com/dnmellen/pycolorterm" rel="nofollow">PyColorTerm</a>):</p> <p>Installation:</p> <pre><code>sudo apt-get install python-pip pip install pycolorterm </code></pre> <p>Python script:</p> <pre><code>from pycolorterm import pycolorterm with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out: out.write('Works OK!') </code></pre> <p>"works OK!" shows in green.</p>
0
2013-09-20T18:06:12Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
21,786,287
<p>Print a string that starts a color/style, then the string, then end the color/style change with <code>'\x1b[0m'</code>:</p> <pre><code>print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m') </code></pre> <p><a href="http://i.stack.imgur.com/RN3MN.png"><img src="http://i.stack.imgur.com/RN3MN.png" alt="Success with green background example"></a></p> <p>Get a table of format options for shell text with following code:</p> <pre><code>def print_format_table(): """ prints table of formatted text format options """ for style in range(8): for fg in range(30,38): s1 = '' for bg in range(40,48): format = ';'.join([str(style), str(fg), str(bg)]) s1 += '\x1b[%sm %s \x1b[0m' % (format, format) print(s1) print('\n') print_format_table() </code></pre> <h1>Light-on-dark example (complete)</h1> <p><a href="http://i.stack.imgur.com/6otvY.png"><img src="http://i.stack.imgur.com/6otvY.png" alt="enter image description here"></a></p> <h1>Dark-on-light example (partial)</h1> <p><img src="http://i.stack.imgur.com/lZr23.png" alt="top part of output"></p>
72
2014-02-14T17:56:38Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
26,445,590
<p>generated a class with all the colors using a for loop to iterate every combination of color up to 100, then wrote a class with python colors. Copy and paste as you will, GPLv2 by me:</p> <pre><code>class colors: '''Colors class: reset all colors with colors.reset two subclasses fg for foreground and bg for background. use as colors.subclass.colorname. i.e. colors.fg.red or colors.bg.green also, the generic bold, disable, underline, reverse, strikethrough, and invisible work with the main class i.e. colors.bold ''' reset='\033[0m' bold='\033[01m' disable='\033[02m' underline='\033[04m' reverse='\033[07m' strikethrough='\033[09m' invisible='\033[08m' class fg: black='\033[30m' red='\033[31m' green='\033[32m' orange='\033[33m' blue='\033[34m' purple='\033[35m' cyan='\033[36m' lightgrey='\033[37m' darkgrey='\033[90m' lightred='\033[91m' lightgreen='\033[92m' yellow='\033[93m' lightblue='\033[94m' pink='\033[95m' lightcyan='\033[96m' class bg: black='\033[40m' red='\033[41m' green='\033[42m' orange='\033[43m' blue='\033[44m' purple='\033[45m' cyan='\033[46m' lightgrey='\033[47m' </code></pre>
15
2014-10-18T23:26:05Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
26,695,185
<p>I wrote a module that handles colors in Linux/OSX/Windows. It supports all 16 colors on all platforms, you can set foreground and background colors at different times, and the string objects give sane results for things like len() and .capitalize().</p> <p><a href="https://github.com/Robpol86/colorclass" rel="nofollow">https://github.com/Robpol86/colorclass</a></p> <p><img src="http://i.stack.imgur.com/j7EjM.png" alt="example on Windows cmd.exe"></p>
2
2014-11-02T01:44:34Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
27,233,961
<p>You can use shell escape characters, that are available from any language. These escape characters start with the ESC character followed by a number of arguments.</p> <p>For example to output a red <code>Hello world</code> string in your terminal:</p> <p><code> echo "\e[31m Hello world \e[0m" </code></p> <p>Or from a python script:</p> <p><code> print "\e[31m Hello world \e[0m" </code></p> <p>Also, I wrote an article about <a href="http://shiroyasha.github.io/escape-sequences-a-quick-guide.html" rel="nofollow">Escape sequences</a> that can probably help you get a better grasp of this mechanism. I hope it will help you.</p>
2
2014-12-01T17:35:07Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
28,159,385
<p>Use pyfancy it is a simple way to do color in the terminal!</p> <p>Example:</p> <p><code> print(pyfancy.RED + "Hello Red" + pyfancy.END) </code></p> <p>Get it at:</p> <p><a href="https://github.com/ilovecode1/pyfancy" rel="nofollow">https://github.com/ilovecode1/pyfancy</a></p>
0
2015-01-26T21:50:24Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
28,388,343
<h2>YAY! another version</h2> <p>while i find <a href="http://stackoverflow.com/a/26445590/3191896">this</a> answer useful, i modified it a bit. this <a href="https://gist.github.com/Jossef/0ee20314577925b4027f">Github Gist</a> is the result</p> <p><strong>usage</strong></p> <pre><code>print colors.draw("i'm yellow", bold=True, fg_yellow=True) </code></pre> <p><img src="http://i.stack.imgur.com/q1mJ3.png" alt="enter image description here"></p> <p>in addition you can wrap common usages:</p> <pre><code>print colors.error('sorry, ') </code></pre> <p><img src="http://i.stack.imgur.com/uGgd7.png" alt="asd"></p> <h3><a href="https://gist.github.com/Jossef/0ee20314577925b4027f">https://gist.github.com/Jossef/0ee20314577925b4027f</a></h3>
9
2015-02-07T22:43:49Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
29,723,536
<p>Stupidly simple based on @joeld's answer</p> <pre><code>class PrintInColor: RED = '\033[91m' GREEN = '\033[92m' YELLOW = '\033[93m' LIGHT_PURPLE = '\033[94m' PURPLE = '\033[95m' END = '\033[0m' @classmethod def red(cls, s, **kwargs): print(cls.RED + s + cls.END, **kwargs) @classmethod def green(cls, s, **kwargs): print(cls.GREEN + s + cls.END, **kwargs) @classmethod def yellow(cls, s, **kwargs): print(cls.YELLOW + s + cls.END, **kwargs) @classmethod def lightPurple(cls, s, **kwargs): print(cls.LIGHT_PURPLE + s + cls.END, **kwargs) @classmethod def purple(cls, s, **kwargs): print(cls.PURPLE + s + cls.END, **kwargs) </code></pre> <p>Then just</p> <pre><code>PrintInColor.red('hello', end=' ') PrintInColor.green('world') </code></pre>
17
2015-04-18T22:18:35Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
29,806,601
<p>If you are using <a href="https://www.djangoproject.com/" rel="nofollow">Django</a> </p> <pre><code>&gt;&gt;&gt; from django.utils.termcolors import colorize &gt;&gt;&gt; print colorize("Hello World!", fg="blue", bg='red', ... opts=('bold', 'blink', 'underscore',)) Hello World! &gt;&gt;&gt; help(colorize) </code></pre> <p>snapshot:</p> <p><img src="http://i.stack.imgur.com/vq4Rs.png" alt="image"></p> <p>(I generally use colored output for debugging on runserver terminal so I added it.)</p> <p><sub> You can test if it is installed in your machine:<br> <code><sub> $ python -c "import django; print django.VERSION"</sub></code><br> To install it check: <a href="https://docs.djangoproject.com/en/1.8/topics/install/" rel="nofollow">How to install Django</a> </sub></p> <p>Give it a Try!!</p>
4
2015-04-22T19:00:32Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
30,564,892
<p>uses ANSI </p> <pre><code>RED = '\033[91m' GREEN = '\033[92m' YELLOW = '\033[93m' LIGHT_PURPLE = '\033[94m' PURPLE = '\033[95m' END = '\033[0m' </code></pre> <p>Make your function :-</p> <pre><code>def red(name): print ("\033[91m {}\033[00m" .format(name)) </code></pre> <p>Call function :- </p> <blockquote> <p>red("Good one") Good one &lt;-- It will print in Red , </p> </blockquote> <p>Note :- not required any module </p>
15
2015-06-01T02:36:18Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
31,310,228
<p>Yet another pypi module that wraps the python 3 print function:</p> <p><a href="https://pypi.python.org/pypi/colorprint/0.1" rel="nofollow">https://pypi.python.org/pypi/colorprint/0.1</a></p> <p>It's usable in python 2.x if you also <code>from __future__ import print</code>.</p>
3
2015-07-09T06:58:08Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
34,443,116
<p>Try this simple code </p> <pre><code>def prRed(prt): print("\033[91m {}\033[00m" .format(prt)) def prGreen(prt): print("\033[92m {}\033[00m" .format(prt)) def prYellow(prt): print("\033[93m {}\033[00m" .format(prt)) def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt)) def prPurple(prt): print("\033[95m {}\033[00m" .format(prt)) def prCyan(prt): print("\033[96m {}\033[00m" .format(prt)) def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt)) def prBlack(prt): print("\033[98m {}\033[00m" .format(prt)) prGreen("Hello world") </code></pre>
21
2015-12-23T20:20:49Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
37,051,472
<p><a href="http://asciimatics.readthedocs.io/en/stable/intro.html" rel="nofollow">asciimatics</a> provides a portable support for building text UI and animations:</p> <pre><code>#!/usr/bin/env python from asciimatics.effects import RandomNoise # $ pip install asciimatics from asciimatics.renderers import SpeechBubble, Rainbow from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.exceptions import ResizeScreenError def demo(screen): render = Rainbow(screen, SpeechBubble('Rainbow')) effects = [RandomNoise(screen, signal=render)] screen.play([Scene(effects, -1)], stop_on_resize=True) while True: try: Screen.wrapper(demo) break except ResizeScreenError: pass </code></pre> <p>Asciicast:</p> <p><a href="https://asciinema.org/a/06sabwtc1bw5wfiq23a71ccxq?autoplay=1" rel="nofollow"><img src="https://asciinema.org/a/06sabwtc1bw5wfiq23a71ccxq.png" alt="rainbow-colored text among ascii noise"></a></p>
0
2016-05-05T13:08:25Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
39,005,305
<p>I ended up doing this, I felt it was cleanest: </p> <pre><code>formatters = { 'RED': '\033[91m', 'GREEN': '\033[92m', 'END': '\033[0m', } print 'Master is currently {RED}red{END}!'.format(**formatters) print 'Help make master {GREEN}green{END} again!'.format(**formatters) </code></pre>
1
2016-08-17T20:01:56Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Print in terminal with colors using Python?
287,871
<p>How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?</p>
1,024
2008-11-13T18:58:10Z
39,452,138
<p>Define a string that starts a color and a string that ends the color, then print your text with the start string at the front and the end string at the end.</p> <pre class="lang-py prettyprint-override"><code>CRED = '\033[91m' CEND = '\033[0m' print(CRED + "Error, does not compute!" + CEND) </code></pre> <p>This produces the following in <code>bash</code>, in <code>urxvt</code> with a Zenburn-style color scheme:</p> <p><a href="http://i.stack.imgur.com/Iu3I1.png" rel="nofollow"><img src="http://i.stack.imgur.com/Iu3I1.png" alt="output colors"></a></p> <p>Through experemintation, we can get more colors:</p> <p><a href="http://i.stack.imgur.com/j7e4i.gif" rel="nofollow"><img src="http://i.stack.imgur.com/j7e4i.gif" alt="color matrix"></a></p> <p>Note: <code>\33[5m</code> and <code>\33[6m</code> are blinking.</p> <p>This way we can create a full color collection:</p> <pre><code>CEND = '\33[0m' CBOLD = '\33[1m' CITALIC = '\33[3m' CURL = '\33[4m' CBLINK = '\33[5m' CBLINK2 = '\33[6m' CSELECTED = '\33[7m' CBLACK = '\33[30m' CRED = '\33[31m' CGREEN = '\33[32m' CYELLOW = '\33[33m' CBLUE = '\33[34m' CVIOLET = '\33[35m' CBEIGE = '\33[36m' CWHITE = '\33[37m' CBLACKBG = '\33[40m' CREDBG = '\33[41m' CGREENBG = '\33[42m' CYELLOWBG = '\33[43m' CBLUEBG = '\33[44m' CVIOLETBG = '\33[45m' CBEIGEBG = '\33[46m' CWHITEBG = '\33[47m' CGREY = '\33[90m' CRED2 = '\33[91m' CGREEN2 = '\33[92m' CYELLOW2 = '\33[93m' CBLUE2 = '\33[94m' CVIOLET2 = '\33[95m' CBEIGE2 = '\33[96m' CWHITE2 = '\33[97m' CGREYBG = '\33[100m' CREDBG2 = '\33[101m' CGREENBG2 = '\33[102m' CYELLOWBG2 = '\33[103m' CBLUEBG2 = '\33[104m' CVIOLETBG2 = '\33[105m' CBEIGEBG2 = '\33[106m' CWHITEBG2 = '\33[107m' </code></pre> <p>Here is the code to generate the test:</p> <pre class="lang-py prettyprint-override"><code>for i in range(24): colors = "" for j in range(5): colors = colors + "\33["+str(x+j)+"m\\33["+str(x+j)+"m\033[0m " print(colors) x=x+ </code></pre>
2
2016-09-12T14:00:32Z
[ "python", "unicode", "terminal", "ansi-colors" ]
Connect to Exchange mailbox with Python
288,546
<p>I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username &amp; password.</p> <p>Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible.</p> <p>In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place!</p> <p>To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).</p>
11
2008-11-13T22:19:01Z
288,569
<p>I'm pretty sure this is going to be impossible without using Outlook and a MAPI profile. If you can sweet talk your mail admin into enabling IMAP on the Exchange server it would make your life a lot easier.</p>
1
2008-11-13T22:28:28Z
[ "python", "email", "connection", "exchange-server", "pywin32" ]
Connect to Exchange mailbox with Python
288,546
<p>I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username &amp; password.</p> <p>Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible.</p> <p>In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place!</p> <p>To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).</p>
11
2008-11-13T22:19:01Z
291,589
<p>You'll have to find a way to run the process as that particular user.</p> <p><a href="http://blogs.msdn.com/mstehle/archive/2007/01/03/myth-cdo-1-21-s-session-logon-parameter-profilepassword-actually-does-something.aspx" rel="nofollow">See this.</a></p> <p>I think <a href="http://docs.activestate.com/activepython/2.5/pywin32/win32process__CreateProcessAsUser_meth.html" rel="nofollow">pywin32.CreateProcessAsUser</a> is the start of the path you need to go down. One last edit. The logged on user handle is obtained from using the <a href="http://docs.activestate.com/activepython/2.5/pywin32/win32security__LogonUser_meth.html" rel="nofollow">win32security.LogonUser</a> method</p>
1
2008-11-14T22:03:54Z
[ "python", "email", "connection", "exchange-server", "pywin32" ]
Connect to Exchange mailbox with Python
288,546
<p>I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username &amp; password.</p> <p>Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible.</p> <p>In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place!</p> <p>To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).</p>
11
2008-11-13T22:19:01Z
519,595
<p>i am looking for something similar - check out <a href="http://code.google.com/p/weboutlook/" rel="nofollow">http://code.google.com/p/weboutlook/</a></p>
1
2009-02-06T08:54:05Z
[ "python", "email", "connection", "exchange-server", "pywin32" ]
Connect to Exchange mailbox with Python
288,546
<p>I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username &amp; password.</p> <p>Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible.</p> <p>In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place!</p> <p>To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).</p>
11
2008-11-13T22:19:01Z
3,072,491
<p>I know this is an old thread, but...</p> <p>If you're using Exchange 2007 or newer, or Office365, take a look at Exchange Web Services. It's a pretty comprehensive SOAP-based interface for Exchange, and you can do pretty much anything Outlook is able to do, including delegate or impersonation access to other user accounts.</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb204119.aspx">http://msdn.microsoft.com/en-us/library/bb204119.aspx</a></p> <p>UPDATE: I have released a <a href="https://pypi.python.org/pypi/exchangelib/">Python EWS client</a> on PyPI that supports autodiscover, calendars, inbox, tasks and contacts</p>
25
2010-06-18T19:21:29Z
[ "python", "email", "connection", "exchange-server", "pywin32" ]
Connect to Exchange mailbox with Python
288,546
<p>I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username &amp; password.</p> <p>Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible.</p> <p>In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place!</p> <p>To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).</p>
11
2008-11-13T22:19:01Z
24,020,665
<p>Ive got it, to connect to outbound exchange you need to connect like this:</p> <pre><code>import smtplib url = YOUR_EXCHANGE_SERVER conn = smtplib.SMTP(url,587) conn.starttls() user,password = (EXCHANGE_USER,EXCHANGE_PASSWORD) conn.login(user,password) </code></pre> <p>now you can send like a normal connection</p> <pre><code>message = 'From: FROMADDR\nTo: TOADDRLIST\nSubject: Your subject\n\n{}' from, to = fromaddr,toaddrs txt = 'This is my message' conn.sendmail(fromaddr,toaddrs,msg.format(txt)) </code></pre> <p>to get the mail from your inbox its a little different</p> <pre><code>import imaplib url = YOUR_EXCHANGE_URL conn = imaplib.IMAP4_SSL(url,993) user,password = (EXCHANGE_USER,EXCHANGE_PASSWORD) conn.login(user,password) conn.select('INBOX') results,data = conn.search(None,'ALL') msg_ids = data[0] msg_id_list = msg_ids.split() </code></pre> <p>this gives you a list of message id' s that you can use to get your emails</p> <pre><code>latest_email_id = msg_id_list[-1] result,data = conn.fetch(latest_email_id,"(RFC822)") raw_email = data[0][1] </code></pre> <p>now raw_email is your email messsage, but its not very pretty, if you want to parse it do somthing like this</p> <pre><code>from email.parser import Parser p = Parser() msg = p.parsestr(raw_email) </code></pre> <p>now you can do</p> <pre><code>msg.get('From') msg.get('Subject') </code></pre> <p>or for the content</p> <pre><code>msg.get_payload() </code></pre> <p>but if its a multipart message your going to need to do a little more processing, luckly a recursive solution is perfect for this situation</p> <pre><code>def process_multipart_message(message): rtn = '' if message.is_multipart(): for m in message.get_payload(): rtn += process_multipart_message(m) else: rtn += message.get_payload() return rtn </code></pre> <p>now </p> <pre><code>msg_contant = process_multipart_message(msg) </code></pre> <p>will give you the whole message every time.</p>
14
2014-06-03T16:48:07Z
[ "python", "email", "connection", "exchange-server", "pywin32" ]
Is it correct to inherit from built-in classes?
288,695
<p>I want to parse an Apache <strong>access.log</strong> file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.</p> <p>I am going to create a class <strong>ApacheAccessLog</strong>, and the only thing I can imagine now, it will be doing is '<strong>readline</strong>' method. Is it conventionally correct to inherit from the builtin <strong>file</strong> class in this case, so the class will behave just like an instance of the <strong>file</strong> class itself, or not? What is the best way of doing that?</p>
6
2008-11-13T23:06:05Z
288,778
<p>It is perfectly acceptable to inherit from a built in class. In this case I'd say you're right on the money. <br> The log "is a" file so that tells you inheritance is ok.. </p> <p>General rule. <br> Dog "is a"n animal, therefore inherit from animal.<br> Owner "has a"n animal therefore don't inherit from animal. </p>
1
2008-11-13T23:40:09Z
[ "python", "inheritance", "oop" ]
Is it correct to inherit from built-in classes?
288,695
<p>I want to parse an Apache <strong>access.log</strong> file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.</p> <p>I am going to create a class <strong>ApacheAccessLog</strong>, and the only thing I can imagine now, it will be doing is '<strong>readline</strong>' method. Is it conventionally correct to inherit from the builtin <strong>file</strong> class in this case, so the class will behave just like an instance of the <strong>file</strong> class itself, or not? What is the best way of doing that?</p>
6
2008-11-13T23:06:05Z
288,783
<p>Although it is in some cases useful to inherit from builtins, the real question here is what you want to do with the output and what's your big-picture design. I would usually write a reader (that uses a file object) and spit out whatever data class I need to hold the information I just read. It's then easy to design that data class to fit in with the rest of my design.</p>
1
2008-11-13T23:42:55Z
[ "python", "inheritance", "oop" ]
Is it correct to inherit from built-in classes?
288,695
<p>I want to parse an Apache <strong>access.log</strong> file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.</p> <p>I am going to create a class <strong>ApacheAccessLog</strong>, and the only thing I can imagine now, it will be doing is '<strong>readline</strong>' method. Is it conventionally correct to inherit from the builtin <strong>file</strong> class in this case, so the class will behave just like an instance of the <strong>file</strong> class itself, or not? What is the best way of doing that?</p>
6
2008-11-13T23:06:05Z
288,807
<p>In this case I would use <em>delegation</em> rather than <em>inheritance</em>. It means that your class should contain the file object as an attribute and invoke a <code>readline</code> method on it. You could pass a file object in the constructor of the logger class.</p> <p>There are at least two reasons for this:</p> <ol> <li>Delegation reduces coupling, for example in place of file objects you can use any other object that implements a <code>readline</code> method (<em>duck typing</em> comes handy here).</li> <li>When inheriting from file the public interface of your class becomes unnecessarily broad. It includes all the methods defined on file even if these methods don't make sense in case of Apache log.</li> </ol>
15
2008-11-13T23:53:29Z
[ "python", "inheritance", "oop" ]
Is it correct to inherit from built-in classes?
288,695
<p>I want to parse an Apache <strong>access.log</strong> file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.</p> <p>I am going to create a class <strong>ApacheAccessLog</strong>, and the only thing I can imagine now, it will be doing is '<strong>readline</strong>' method. Is it conventionally correct to inherit from the builtin <strong>file</strong> class in this case, so the class will behave just like an instance of the <strong>file</strong> class itself, or not? What is the best way of doing that?</p>
6
2008-11-13T23:06:05Z
288,884
<p>You should be fairly safe inheriting from a "builtin" class, as later modifications to these classes will usually be compatible with the current version. </p> <p>However, you should think seriously about wether you really want to tie your class to the additional functionality provided by the builtin class. As mentioned in another answer you should consider (perhaps even prefer) using <em>delegation</em> instead. </p> <p>As an example of why to avoid inheritance if you don't need it you can look at the <em>java.util.Stack</em> class. As it extends Vector it inherits <strong>all</strong> of the methods on Vector. Most of these methods break the contract implied by Stack, e.g. LIFO. It would have been much better to implement Stack using a Vector internally, only exposing Stack methods as the API. It would then have been easy to change the implementation to ArrayList or something else later, none of which is possible now due to inheritance.</p>
1
2008-11-14T00:31:59Z
[ "python", "inheritance", "oop" ]
Is it correct to inherit from built-in classes?
288,695
<p>I want to parse an Apache <strong>access.log</strong> file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.</p> <p>I am going to create a class <strong>ApacheAccessLog</strong>, and the only thing I can imagine now, it will be doing is '<strong>readline</strong>' method. Is it conventionally correct to inherit from the builtin <strong>file</strong> class in this case, so the class will behave just like an instance of the <strong>file</strong> class itself, or not? What is the best way of doing that?</p>
6
2008-11-13T23:06:05Z
307,776
<p>I am coming from a Java background but I am fairly confident that the same principles will apply in Python. As a rule of thumb you should <b>never</b> inherit from a class whose implementation you don't understand and control unless that class has been designed specifically for inheritance. If it has been designed in this way it should describe this clearly in its documentation.</p> <p>The reason for this is that inheritance can potentially bind you to the implementation details of the class that you are inheriting from.</p> <p>To use an example from Josh Bloch's book 'Effective Java'</p> <p>If we were to extend the class <code>ArrayList</code> class in order to be able to count the number of items that were added to it during its life-time (not necessarily the number it currently contains) we may be tempted to write something like this.</p> <pre><code>public class CountingList extends ArrayList { int counter = 0; public void add(Object o) { counter++; super.add(0); } public void addAll(Collection c) { count += c.size(); super.addAll(c); } // Etc. } </code></pre> <p>Now this extension looks like it would accurately count the number of elements that were added to the list but in fact it may not. If <code>ArrayList</code> has implemented <code>addAll</code> by iterating over the <code>Collection</code> provided and calling its interface method <code>addAll</code> for each element then we will count each element added through the <code>addAll</code> method twice. Now the behaviour of our class is dependent on the implementation details of <code>ArrayList</code>.</p> <p>This is of course in addition to the disadvantage of not being able to use other implementations of <code>List</code> with our <code>CountingList</code> class. Plus the disadvantages of inheriting from a concrete class that are discussed above.</p> <p>It is my understanding that Python uses a similar (if not identical) method dispatch mechanism to Java and will therefore be subject to the same limitations. If someone could provide an example in Python I'm sure it would be even more useful.</p>
6
2008-11-21T03:48:15Z
[ "python", "inheritance", "oop" ]
Is it correct to inherit from built-in classes?
288,695
<p>I want to parse an Apache <strong>access.log</strong> file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.</p> <p>I am going to create a class <strong>ApacheAccessLog</strong>, and the only thing I can imagine now, it will be doing is '<strong>readline</strong>' method. Is it conventionally correct to inherit from the builtin <strong>file</strong> class in this case, so the class will behave just like an instance of the <strong>file</strong> class itself, or not? What is the best way of doing that?</p>
6
2008-11-13T23:06:05Z
312,981
<p>You seem to have found your answer that in this case delegation is the better strategy. Nevertheless, I would like to add that, excepting delegation, there is nothing wrong with extending a built-in class, particularly if your alternative, depending on the language, is "monkey patching" (see <a href="http://en.wikipedia.org/wiki/Monkey_patch" rel="nofollow">http://en.wikipedia.org/wiki/Monkey_patch</a>) </p>
0
2008-11-23T21:26:35Z
[ "python", "inheritance", "oop" ]
Can I use named groups in a Perl regex to get the results in a hash?
288,968
<p>Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the <code>$n</code> values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.</p> <p>Python does it like so:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = re.compile(r'(?P&lt;count&gt;\d+)') &gt;&gt;&gt; match = regex.match('42') &gt;&gt;&gt; print match.groupdict() {'count': '42'} </code></pre> <p>I know the <code>?P</code> indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?</p>
14
2008-11-14T01:28:40Z
288,983
<p>AFIK <a href="http://en.wikipedia.org/wiki/PCRE" rel="nofollow">PCRE</a> has named group capturing as:</p> <pre><code>(?'NAME'pattern) (?&lt;NAME&gt;pattern) </code></pre> <p>You can find info <a href="http://perldoc.perl.org/perlre.html#Extended-Patterns" rel="nofollow">here</a>.</p>
4
2008-11-14T01:38:01Z
[ "python", "regex", "perl" ]
Can I use named groups in a Perl regex to get the results in a hash?
288,968
<p>Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the <code>$n</code> values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.</p> <p>Python does it like so:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = re.compile(r'(?P&lt;count&gt;\d+)') &gt;&gt;&gt; match = regex.match('42') &gt;&gt;&gt; print match.groupdict() {'count': '42'} </code></pre> <p>I know the <code>?P</code> indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?</p>
14
2008-11-14T01:28:40Z
288,989
<p>Perl uses <code>(?&lt;NAME&gt;pattern)</code> to specify names captures. You have to use the <code>%+</code> hash to retrieve them.</p> <pre><code>$variable =~ /(?&lt;count&gt;\d+)/; print "Count is $+{count}"; </code></pre> <p>This is only supported on Perl 5.10 and higher though.</p>
31
2008-11-14T01:40:02Z
[ "python", "regex", "perl" ]
Can I use named groups in a Perl regex to get the results in a hash?
288,968
<p>Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the <code>$n</code> values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.</p> <p>Python does it like so:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = re.compile(r'(?P&lt;count&gt;\d+)') &gt;&gt;&gt; match = regex.match('42') &gt;&gt;&gt; print match.groupdict() {'count': '42'} </code></pre> <p>I know the <code>?P</code> indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?</p>
14
2008-11-14T01:28:40Z
289,149
<p>As of Perl 5.10, Perl regexes support <a href="http://perldoc.perl.org/perlre.html#PCRE%2fPython-Support">some Python features</a>, making them <em>Python</em> compatible regexes, I guess. The Python versions have the "P" in them, but all of these work in Perl 5.10. See the <a href="http://perldoc.perl.org/perlre.html">perlre</a> documentation for the details:</p> <p>Define a named capture buffer. Equivalent to <code>(?&lt;NAME&gt;pattern)</code>.</p> <pre><code>(?P&lt;NAME&gt;pattern) </code></pre> <p>Backreference to a named capture buffer. Equivalent to <code>\g{NAME}</code>.</p> <pre><code>(?P=NAME) </code></pre> <p>Subroutine call to a named capture buffer. Equivalent to <code>(?&amp;NAME)</code>.</p> <pre><code>(?P&gt;NAME) </code></pre> <p>Although I didn't add the Python-compatibility to the latest edition of <a href="http://oreilly.com/catalog/9780596520106/">Learning Perl</a>, we do cover the new Perl 5.10 features, including named captures.</p>
16
2008-11-14T03:14:48Z
[ "python", "regex", "perl" ]
Can I use named groups in a Perl regex to get the results in a hash?
288,968
<p>Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the <code>$n</code> values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.</p> <p>Python does it like so:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = re.compile(r'(?P&lt;count&gt;\d+)') &gt;&gt;&gt; match = regex.match('42') &gt;&gt;&gt; print match.groupdict() {'count': '42'} </code></pre> <p>I know the <code>?P</code> indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?</p>
14
2008-11-14T01:28:40Z
1,091,618
<p>As couple of people said perl 5.10 has named groups.</p> <p>But in previous perls you can do something, not as convenient, but relatively nice:</p> <pre><code>my %hash; @hash{"count", "something_else"} = $string =~ /(\d+)\s*,\s*(\S+)/; </code></pre> <p>and then you can use:</p> <p>$hash{"count"} and $hash{"something_else"}.</p>
8
2009-07-07T10:44:31Z
[ "python", "regex", "perl" ]
receiving data over a python socket
289,035
<p>I'm making a program that retrieves decently large amounts of data through a python socket and then immediately disconnects when the information is finished sending. But I'm not sure how to do this</p> <p>All the examples on the web are of tcp clients where they have</p> <pre><code>while 1: data = sock.recv(1024) </code></pre> <p>But this creates a look to infinite loop to receive data via the socket, does it not?</p> <p>I need to figure out the size of the message coming in and loop through it in buffer-sized increments to get the full message. And after the message has finished sending, I would like to disconnect, although i think the connection will be closed from the other end. Any help would be nice</p> <p>Thanks</p>
4
2008-11-14T02:04:45Z
289,046
<p>You've probably missed a very important part of those <a href="http://docs.python.org/library/socket.html#example">examples</a> - the lines that follow the "recv()" call:</p> <pre><code>while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() </code></pre>
15
2008-11-14T02:10:28Z
[ "python", "sockets" ]
Google AppEngine App Version
289,174
<p>Is it possible to fetch the current application version programmatically for use in urls with far future expires header?</p> <p>For example:</p> <pre><code>&lt;link rel="stylesheet" href="app.js?v=1.23" /&gt; </code></pre> <p>Should be automatically updated to:</p> <pre><code>&lt;link rel="stylesheet" href="app.js?v=1.24" /&gt; </code></pre> <p>In order to do so I need to get the version.</p>
2
2008-11-14T03:39:49Z
293,095
<p>From [<a href="http://code.google.com/appengine/docs/python/theenvironment.html">http://code.google.com/appengine/docs/python/theenvironment.html</a>][1]</p> <pre><code>from google.appengine.ext import webapp import os class PrintEnvironmentHandler(webapp.RequestHandler): def get(self): for name in os.environ.keys(): self.response.out.write("%s = %s&lt;br /&gt;\n" % (name, os.environ[name])) [1]: http://code.google.com/appengine/docs/python/theenvironment.html </code></pre>
5
2008-11-15T21:49:31Z
[ "python", "google-app-engine" ]
Why does Excel macro work in Excel but not when called from Python?
289,187
<p>I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message:</p> <p>' Run-time error '1004': Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by VisualBasic. '</p> <p>The macro has code like the following:</p> <pre><code>Sheets("CC").Delete ActiveWindow.View = xlPageBreakPreview Sheets("FY").Copy After:=Sheets(Sheets.Count) Sheets(Sheets.Count).Name = "CC" </code></pre> <p>and the debugger highlights the error on the last line where the sheet is renamed. I've also tried putting these calls directly in python but get the same error message.</p> <p>Any suggestions are much appreciated!</p> <p>Thanks.</p>
0
2008-11-14T03:45:51Z
289,313
<p>I ran the code inside Excel VBA.<br> I am guessing that the following line is failing.<br></p> <p><code> Sheets("CC").Delete </code></p> <p>And that is the reason, you can't give the new sheet same name as existing (non-deleted) sheet.<br> </p> <p>Put <code> Application.DisplayAlerts = False </code> before <code> Sheets("CC").Delete </code> and <br> <code> Application.DisplayAlerts = True </code> once you are finished with the code.</p> <p>I haven't used python but it seems the library is swallowing that error for you and letting you go ahead to the next statement.</p> <p>Hope that helps.</p>
2
2008-11-14T05:29:29Z
[ "python", "excel", "vba", "pywin32" ]
Why does Excel macro work in Excel but not when called from Python?
289,187
<p>I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message:</p> <p>' Run-time error '1004': Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by VisualBasic. '</p> <p>The macro has code like the following:</p> <pre><code>Sheets("CC").Delete ActiveWindow.View = xlPageBreakPreview Sheets("FY").Copy After:=Sheets(Sheets.Count) Sheets(Sheets.Count).Name = "CC" </code></pre> <p>and the debugger highlights the error on the last line where the sheet is renamed. I've also tried putting these calls directly in python but get the same error message.</p> <p>Any suggestions are much appreciated!</p> <p>Thanks.</p>
0
2008-11-14T03:45:51Z
289,482
<p>Behind the scenes, VB and VBA are maintaining references to COM objects for the application, worksheets etc. This is why you have the globals 'Application', 'Worksheets' etc. It is possible that VBA is still holding a reference to the worksheet, so Excel hasn't tidied it up properly.</p> <p>Try not using these implicit globals and referencing the items in the object model explicitly. Alternatively you could do it directly in Python.</p> <p>Here's a python script that will do something like what you want:</p> <pre><code>import win32com.client xl = win32com.client.Dispatch ('Excel.Application') xl.Visible = True wb = xl.Workbooks.Add() wb.Worksheets[0].Delete() wb.Worksheets.Add() wb.Worksheets[0].Name = 'Sheet1' </code></pre>
1
2008-11-14T08:17:32Z
[ "python", "excel", "vba", "pywin32" ]
py2exe setup.py with icons
289,518
<p>How do I make icons for my exe file when compiling my Python program?</p>
5
2008-11-14T08:41:21Z
289,544
<p>I was searching for this a while ago, and found this: <a href="http://www.mail-archive.com/[email protected]/msg05619.html" rel="nofollow">http://www.mail-archive.com/[email protected]/msg05619.html</a></p> <p>Quote from above link:</p> <blockquote> <p>The setup.py File: PY_PROG =</p> <p>'trek10.py' APP_NAME = 'Trek_Game'</p> <p>cfg = {</p> <pre><code>'name':APP_NAME, 'version':'1.0', 'description':'', 'author':'', 'author_email':'', 'url':'', 'py2exe.target':'', 'py2exe.icon':'icon.ico', #64x64 'py2exe.binary':APP_NAME, #leave off the .exe, it will be added 'py2app.target':'', 'py2app.icon':'icon.icns', #128x128 'cx_freeze.cmd':'~/src/cx_Freeze-3.0.3/FreezePython', 'cx_freeze.target':'', 'cx_freeze.binary':APP_NAME, } </code></pre> <p>--snip--</p> </blockquote>
2
2008-11-14T08:57:38Z
[ "python", "icons", "py2exe" ]
py2exe setup.py with icons
289,518
<p>How do I make icons for my exe file when compiling my Python program?</p>
5
2008-11-14T08:41:21Z
289,560
<p>I have no experience with py2exe but a quick <a href="http://www.google.com/search?q=py2exe+embed+icon" rel="nofollow">google search</a> found <a href="http://www.py2exe.org/index.cgi/CustomIcons" rel="nofollow">this</a>, if <em>embedding</em> icons in exe files was what you asked for. </p> <p>If you want to <em>create</em> .ico files, I'd really suggest you search for a icon designer or finished icons. Sure you <em>can</em> create a Win 3.x style icon fairly easy by creating a 16x16, 32x32, or 64x64 px image in paint, and rename it to .ico. But to create modern multi resolution icons for windows is a lot more complicated.</p> <p>(I was about to ask what OS you was compiling for, when I realized "exe" sounds very windows, and sure enough...)</p>
-1
2008-11-14T09:06:43Z
[ "python", "icons", "py2exe" ]
py2exe setup.py with icons
289,518
<p>How do I make icons for my exe file when compiling my Python program?</p>
5
2008-11-14T08:41:21Z
289,590
<p>Linking the icons is answered in other answers. Creating the thing is as easy as using <a href="http://winterdrache.de/freeware/png2ico/" rel="nofollow">png2ico</a>. It creates an ico file from 1 or more png's and handles multiple sizes etc, like:</p> <pre><code>png2ico myicon.ico logo16x16.png logo32x32.png </code></pre> <p>Will create myicon.ico with sizes 16x16 and 32x32. Sizes must be multiples of 8 squares, and no larger than 256x256.</p>
2
2008-11-14T09:23:37Z
[ "python", "icons", "py2exe" ]
py2exe setup.py with icons
289,518
<p>How do I make icons for my exe file when compiling my Python program?</p>
5
2008-11-14T08:41:21Z
418,579
<p>py2exe is a little dated, and has been continued with pyinstaller (which itself is a little dated; the svn release is the most up to date) <a href="http://pyinstaller.python-hosting.com/" rel="nofollow">http://pyinstaller.python-hosting.com/</a></p> <p>After running through the initial scripts for pyinstaller and generating the spec file from Makespec.py, edit the spec file and look for the EXE section. At the tail end of that just add in your ico definition; so</p> <blockquote> <p>console=True)</p> </blockquote> <p>would become</p> <blockquote> <p>console=True, icon='mine.ico' )</p> </blockquote> <p>That is, if the mine.ico file were in the same folder as the Makespec.py file. There's also a command line option for feeding the icon into it. I think it was </p> <pre><code>python Makespec.py -i 'mine.ico' /path/to/file.py </code></pre>
2
2009-01-06T23:16:00Z
[ "python", "icons", "py2exe" ]
How do I use my icons when compiling my python program with py2exe?
289,668
<p>I don't know what commands to enter into the setup.py file when compiling a python program to use my icons. Can anyone help me? Thanks in advance.</p>
3
2008-11-14T09:59:48Z
289,723
<p>I haven't tried this, but here's a link I found:</p> <p><a href="http://www.py2exe.org/index.cgi/CustomIcons" rel="nofollow">http://www.py2exe.org/index.cgi/CustomIcons</a></p>
4
2008-11-14T10:34:53Z
[ "python", "py2exe" ]
How do I use my icons when compiling my python program with py2exe?
289,668
<p>I don't know what commands to enter into the setup.py file when compiling a python program to use my icons. Can anyone help me? Thanks in advance.</p>
3
2008-11-14T09:59:48Z
289,784
<pre><code>from distutils.core import setup import py2exe setup( windows=[{"script": 'app.py', "icon_resources": [(1, "icon.ico")]}], options={"py2exe":{"unbuffered": True, "optimize": 2, "bundle_files" : 1, "dist_dir": "bin"}}, zipfile = "lib.zip", ) </code></pre>
5
2008-11-14T11:03:57Z
[ "python", "py2exe" ]
How can I improve this number2words script
289,735
<pre><code>import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) &lt; 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) </code></pre> <p><strong>Warning</strong>: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.</p> <p><strong>Edit</strong>: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.</p>
3
2008-11-14T10:40:21Z
289,748
<p>Two improvements come to mind:</p> <ul> <li>40 is spelled "forty", not "fourty"</li> <li>your program needs unit tests</li> </ul> <p>Have a look at the Python <a href="http://python.org/doc/2.5/lib/module-doctest.html" rel="nofollow">doctest</a> and <a href="http://python.org/doc/2.5/lib/module-unittest.html" rel="nofollow">unittest</a> modules.</p>
3
2008-11-14T10:45:32Z
[ "python" ]
How can I improve this number2words script
289,735
<pre><code>import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) &lt; 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) </code></pre> <p><strong>Warning</strong>: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.</p> <p><strong>Edit</strong>: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.</p>
3
2008-11-14T10:40:21Z
289,765
<p>Maybe <a href="http://code.activestate.com/recipes/413172/" rel="nofollow">Numbers and plural words as spoken English</a> will help a little. A little dated though - 4 May 2005.</p>
1
2008-11-14T10:53:49Z
[ "python" ]
How can I improve this number2words script
289,735
<pre><code>import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) &lt; 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) </code></pre> <p><strong>Warning</strong>: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.</p> <p><strong>Edit</strong>: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.</p>
3
2008-11-14T10:40:21Z
289,766
<p>You can't group digits into "segments" going from left-to-right. The <code>range(0,len(),3)</code> is not going to work out well. You'll have to write the same algorithm for inserting digit separators. You start from the right, picking off segments of digits.</p> <p>What's left over (on the left, get it?) will be 1, 2 or 3 digits. You've got convertTrio and convertDuo, which handle 3 and 2 digits, respectively. Somewhere in there is a convert one digit function (can't see it).</p> <p>If it's not homework, then, here's a proper digit clustering algorithm</p> <pre><code>def segment( n ): segList= [] while len(n) &gt; 3: segList.insert( 0, n[-3:] ) n= n[:-3] segList.insert( 0, n ) return segList </code></pre> <p>Edit</p> <p>To be more Pythonic, package this as a tidy, reusable module. The stuff inside the <code>if __name__ == "__main__"</code> does two things, which should be separated.</p> <p>Your command-line parsing (anything having to do with <code>sys.argv</code> is one thing. The actual "convert a number" function is something else entirely. You want to look more like this.</p> <pre><code>if __name__ == "__main__": import sys for number in sys.argv[1:]: print number2string( number ) </code></pre> <p>Then, your <code>number2string</code> function becomes an easily reused piece of this module.</p>
2
2008-11-14T10:54:29Z
[ "python" ]
How can I improve this number2words script
289,735
<pre><code>import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) &lt; 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) </code></pre> <p><strong>Warning</strong>: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.</p> <p><strong>Edit</strong>: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.</p>
3
2008-11-14T10:40:21Z
289,828
<p>Check out source for <a href="http://search.cpan.org/src/LHOWARD/Number-Spell-0.04/Spell.pm" rel="nofollow">Number::Spell</a> Perl module. It is short and can be easily ported to Python (if it has not already been done).</p>
0
2008-11-14T11:24:35Z
[ "python" ]
How can I improve this number2words script
289,735
<pre><code>import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) &lt; 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) </code></pre> <p><strong>Warning</strong>: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.</p> <p><strong>Edit</strong>: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.</p>
3
2008-11-14T10:40:21Z
290,706
<p>Instead of slicing digits, use modular arithmetic to separate the units. This function will convert a number less than 100 using the given data structures.</p> <pre><code>def convert(n): q, r = divmod(n, 10) if q &lt; 2: return words[n] result = tens[q-1] # offset because tens is missing first null value if r: result += '-' + words[r] return result </code></pre> <p>Then use convert recursively to support larger numbers, e.g., start with divmod(n, 100) and so on.</p>
2
2008-11-14T16:45:41Z
[ "python" ]
How can I improve this number2words script
289,735
<pre><code>import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen', 19 : 'nineteen' } tens = [ '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', ] placeholders = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion' ] # segMag = segment magnitude (starting at 1) def convertTrio(number): return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3]) def convertDuo(number): #if teens or less if int(number[0]) == 1: return words[int(number)] #twenty-five else: return tens[int(number[0]) - 1] + '-' + words[int(number[1])] if __name__ == "__main__": string = [] numeralSegments = [] numeral = sys.argv[1] if int(numeral) &lt; 100: print convertDuo(numeral) else: # split number into lists, grouped in threes for i in range (0, len(numeral), 3): numeralSegments.append(numeral[i:i+3]) numeralSegments.reverse() # for every segment, convert to trio word and append thousand, million, etc depending on magnitude for i in range (len(numeralSegments)): string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i]) # reverse the list of strings before concatenating to commas string.reverse() print ', '.join(string) </code></pre> <p><strong>Warning</strong>: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.</p> <p><strong>Edit</strong>: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.</p>
3
2008-11-14T10:40:21Z
3,217,210
<p>In case anyone reading this is looking for a numbers to words script, have a look at <a href="http://pypi.python.org/pypi/inflect" rel="nofollow">inflect.py</a></p> <pre><code>import inflect p = inflect.engine() p.numwords(123456789) </code></pre> <p>gives</p> <pre><code>'one hundred and twenty-three million, four hundred and fifty-six thousand, seven hundred and eighty-nine' </code></pre>
0
2010-07-09T23:55:19Z
[ "python" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
290,009
<p>I use <a href="http://www.sqlalchemy.org/">SQL Alchemy</a> with cPython (I don't know if it'll work with IronPython though). It'll be pretty familiar to you if you've used Hibernate/nHibernate. If that's a bit too verbose for you, you can use <a href="http://elixir.ematia.de/trac/wiki">Elixir</a>, which is a thin layer on top of SQL Alchemy. To use either one of those, you'll need <a href="http://pyodbc.sourceforge.net/">pyodbc</a>, but that's a pretty simple install.</p> <p>Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc.</p>
16
2008-11-14T13:02:21Z
[ "python", "sql-server", "ironpython" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
290,105
<p>I also successfully use <a href="http://pymssql.sourceforge.net/" rel="nofollow">pymssql</a> with CPython. (With and without SQLAlchemy).</p>
3
2008-11-14T13:39:35Z
[ "python", "sql-server", "ironpython" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
291,437
<p>I've used <a href="http://www.pymssql.org/" rel="nofollow">pymssql</a> with standard python and liked it. Probably easier than the alternatives mentioned if you're <em>just</em> looking for basic database access.</p> <p>Sample <a href="http://www.pymssql.org/pymssql_examples.html" rel="nofollow">code</a>.</p>
1
2008-11-14T21:08:49Z
[ "python", "sql-server", "ironpython" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
291,473
<p>pyodbc comes with Activestate Python, which can be downloaded from <a href="http://www.activestate.com/store/productdetail.aspx?prdGuid=b08b04e0-6872-4d9d-a722-7a0c2dea2758" rel="nofollow">here</a>. A minimal odbc script to connect to a SQL Server 2005 database looks like this:</p> <pre><code>import odbc CONNECTION_STRING=""" Driver={SQL Native Client}; Server=[Insert Server Name Here]; Database=[Insert DB Here]; Trusted_Connection=yes; """ db = odbc.odbc(CONNECTION_STRING) c = db.cursor() c.execute ('select foo from bar') rs = c.fetchall() for r in rs: print r[0] </code></pre>
11
2008-11-14T21:17:14Z
[ "python", "sql-server", "ironpython" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
301,746
<p>Everyone else seems to have the cPython -> SQL Server side covered. If you want to use IronPython, you can use the standard ADO.NET API to talk to the database:</p> <pre><code>import clr clr.AddReference('System.Data') from System.Data.SqlClient import SqlConnection, SqlParameter conn_string = 'data source=&lt;machine&gt;; initial catalog=&lt;database&gt;; trusted_connection=True' connection = SqlConnection(conn_string) connection.Open() command = connection.CreateCommand() command.CommandText = 'select id, name from people where group_id = @group_id' command.Parameters.Add(SqlParameter('group_id', 23)) reader = command.ExecuteReader() while reader.Read(): print reader['id'], reader['name'] connection.Close() </code></pre> <p>If you've already got IronPython, you don't need to install anything else.</p> <p>Lots of docs available <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx">here</a> and <a href="http://www.ironpython.info/index.php/Contents#Databases">here</a>.</p>
23
2008-11-19T12:27:37Z
[ "python", "sql-server", "ironpython" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
782,123
<p><a href="http://adodbapi.sourceforge.net/" rel="nofollow">http://adodbapi.sourceforge.net/</a> can be used with either CPython or IronPython. I have been very pleased with it.</p>
3
2009-04-23T14:54:22Z
[ "python", "sql-server", "ironpython" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
7,422,797
<p>If you are want the quick and dirty way with CPython (also works for 3.X python):</p> <p>Install PYWIN32 after you install python <a href="http://sourceforge.net/projects/pywin32/files/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/files/pywin32/</a></p> <p>Import the following library: import odbc</p> <p>I created the following method for getting the SQL Server odbc driver (it is slightly different in naming depending on your version of Windows, so this will get it regardless):</p> <pre><code>def getSQLServerDriver(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\ODBC\ODBCINST.INI") sqlServerRegExp = re.compile('sql.*server', re.I | re.S) try: for i in range(0, 2048): folder = winreg.EnumKey(key, i) if sqlServerRegExp.match(folder): return folder.strip() except WindowsError: pass </code></pre> <p>Note: if you use the above function, you'll need to also import these two libraries: winreg and re</p> <p>Then you use the odbc API 1 information as defined here: <a href="http://www.python.org/dev/peps/pep-0248/" rel="nofollow">http://www.python.org/dev/peps/pep-0248/</a></p> <p>Your connection interface string should look something like this (assuming you are using my above method for getting the ODBC driver name, and it is a trusted connection):</p> <pre><code>dbString = "Driver={SQLDriver};Server=[SQL Server];Database=[Database Name];Trusted_Connection=yes;".replace('{SQLDriver}', '{' + getSQLServerDriver() + '}') </code></pre> <p>This method has many down sides. It is clumsy because of only supporting ODBC API 1, and there are a couple minor bugs in either the API or the ODBC driver that I've run across, but it does get the job done in all versions of CPython in Windows.</p>
0
2011-09-14T20:48:50Z
[ "python", "sql-server", "ironpython" ]
What's the simplest way to access mssql with python or ironpython?
289,978
<p>I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.</p> <p>Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.</p>
21
2008-11-14T12:50:11Z
12,613,800
<p><a href="http://code.google.com/p/pypyodbc" rel="nofollow" title="PyPyODBC">PyPyODBC</a> (<a href="http://code.google.com/p/pypyodbc" rel="nofollow">http://code.google.com/p/pypyodbc</a>) works under PyPy, Ironpython and CPython.</p> <p><a href="https://code.google.com/p/pypyodbc/wiki/A_HelloWorld_sample_to_access_mssql_with_python" rel="nofollow">This article</a> shows a Hello World sample of accessing mssql in Python.</p> <p>PyPyODBC has almostly same usage as pyodbc, as it can been seen as a re-implemenation of the pyodbc moudle. Because it's written in pure Python, it can also run on IronPython and PyPy.</p> <p>Actually, when switch to pypyodbc in your existing script, you can do this:</p> <pre><code>#import pyodbc &lt;-- Comment out the original pyodbc importing line import pypyodbc as pyodbc # Let pypyodbc "pretend" the pyodbc pyodbc.connect(...) # pypyodbc has 99% same APIs as pyodbc ... </code></pre>
1
2012-09-27T03:49:08Z
[ "python", "sql-server", "ironpython" ]
Django Template System: How do I solve this looping / grouping / counting?
290,397
<p>I have a list of articles, and each article belongs to a section.</p> <pre><code>class Section(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Article(models.Model): section = models.ForeignKey(Section) headline = models.CharField(max_length=200) # ... </code></pre> <p>I want to display the articles, grouped by section.</p> <pre> Sponsorships, Advertising & Marketing 1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams 2. Phil Jackson Questions Harrah's Signage At New Orleans Arena 3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account 4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider 5. Marketplace Roundup Sports Media 6. Many Patriots Fans In New England Will Not See Tonight's Game 7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation 8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09 9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic 10. Media Notes Leagues & Governing Bodies 11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team 12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed 13. Average Ticket Price For NFL Playoff Games To Drop By 10% </pre> <p>I figured out how to do most of it with Django's template system.</p> <pre><code>{% regroup articles by section as articles_by_section %} {% for article in articles_by_section %} &lt;h4&gt;{{ article.grouper }}&lt;/h4&gt; &lt;ul&gt; {% for item in article.list %} &lt;li&gt;{{ forloop.counter }}. {{ item.headline }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} </code></pre> <p>I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?</p>
3
2008-11-14T15:21:32Z
290,414
<p>I think you can use forloop.parentloop.counter inside of the inner loop to achieve the numbering you're after.</p>
-1
2008-11-14T15:25:47Z
[ "python", "django", "django-templates" ]
Django Template System: How do I solve this looping / grouping / counting?
290,397
<p>I have a list of articles, and each article belongs to a section.</p> <pre><code>class Section(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Article(models.Model): section = models.ForeignKey(Section) headline = models.CharField(max_length=200) # ... </code></pre> <p>I want to display the articles, grouped by section.</p> <pre> Sponsorships, Advertising & Marketing 1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams 2. Phil Jackson Questions Harrah's Signage At New Orleans Arena 3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account 4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider 5. Marketplace Roundup Sports Media 6. Many Patriots Fans In New England Will Not See Tonight's Game 7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation 8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09 9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic 10. Media Notes Leagues & Governing Bodies 11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team 12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed 13. Average Ticket Price For NFL Playoff Games To Drop By 10% </pre> <p>I figured out how to do most of it with Django's template system.</p> <pre><code>{% regroup articles by section as articles_by_section %} {% for article in articles_by_section %} &lt;h4&gt;{{ article.grouper }}&lt;/h4&gt; &lt;ul&gt; {% for item in article.list %} &lt;li&gt;{{ forloop.counter }}. {{ item.headline }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} </code></pre> <p>I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?</p>
3
2008-11-14T15:21:32Z
291,005
<p>You could just use an ordered list instead of unordered:</p> <pre><code>{% regroup articles by section as articles_by_section %} &lt;ol&gt; {% for article in articles_by_section %} &lt;h4&gt;{{ article.grouper }}&lt;/h4&gt; {% for item in article.list %} &lt;li&gt;{{ item.headline }}&lt;/li&gt; {% endfor %} {% endfor %} &lt;/ol&gt; </code></pre>
-1
2008-11-14T18:50:39Z
[ "python", "django", "django-templates" ]
Django Template System: How do I solve this looping / grouping / counting?
290,397
<p>I have a list of articles, and each article belongs to a section.</p> <pre><code>class Section(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Article(models.Model): section = models.ForeignKey(Section) headline = models.CharField(max_length=200) # ... </code></pre> <p>I want to display the articles, grouped by section.</p> <pre> Sponsorships, Advertising & Marketing 1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams 2. Phil Jackson Questions Harrah's Signage At New Orleans Arena 3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account 4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider 5. Marketplace Roundup Sports Media 6. Many Patriots Fans In New England Will Not See Tonight's Game 7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation 8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09 9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic 10. Media Notes Leagues & Governing Bodies 11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team 12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed 13. Average Ticket Price For NFL Playoff Games To Drop By 10% </pre> <p>I figured out how to do most of it with Django's template system.</p> <pre><code>{% regroup articles by section as articles_by_section %} {% for article in articles_by_section %} &lt;h4&gt;{{ article.grouper }}&lt;/h4&gt; &lt;ul&gt; {% for item in article.list %} &lt;li&gt;{{ forloop.counter }}. {{ item.headline }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} </code></pre> <p>I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?</p>
3
2008-11-14T15:21:32Z
309,327
<p>Following <a href="#290414" rel="nofollow">Jeb's suggeston in a comment</a>, I created a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags" rel="nofollow">custom template tag</a>.</p> <p>I replaced <code>{{ forloop.counter }}</code> with <code>{% counter %}</code>, a tag that simply prints how many times it's been called.</p> <p>Here's the code for my counter tag. </p> <pre><code>class CounterNode(template.Node): def __init__(self): self.count = 0 def render(self, context): self.count += 1 return self.count @register.tag def counter(parser, token): return CounterNode() </code></pre>
4
2008-11-21T16:23:07Z
[ "python", "django", "django-templates" ]
Django Template System: How do I solve this looping / grouping / counting?
290,397
<p>I have a list of articles, and each article belongs to a section.</p> <pre><code>class Section(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name class Article(models.Model): section = models.ForeignKey(Section) headline = models.CharField(max_length=200) # ... </code></pre> <p>I want to display the articles, grouped by section.</p> <pre> Sponsorships, Advertising & Marketing 1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams 2. Phil Jackson Questions Harrah's Signage At New Orleans Arena 3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account 4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider 5. Marketplace Roundup Sports Media 6. Many Patriots Fans In New England Will Not See Tonight's Game 7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation 8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09 9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic 10. Media Notes Leagues & Governing Bodies 11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team 12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed 13. Average Ticket Price For NFL Playoff Games To Drop By 10% </pre> <p>I figured out how to do most of it with Django's template system.</p> <pre><code>{% regroup articles by section as articles_by_section %} {% for article in articles_by_section %} &lt;h4&gt;{{ article.grouper }}&lt;/h4&gt; &lt;ul&gt; {% for item in article.list %} &lt;li&gt;{{ forloop.counter }}. {{ item.headline }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} </code></pre> <p>I just can't figure out how to do the numbers. The code above numbers the articles in Sports Media 1-5 instead of 6-10. Any suggestions?</p>
3
2008-11-14T15:21:32Z
359,197
<p>This isn't exactly neat, but may be appropriate for someone:</p> <pre><code>{% for article in articles %} {% ifchanged article.section %} {% if not forloop.first %}&lt;/ul&gt;{% endif %} &lt;h4&gt;{{article.section}}&lt;/h4&gt; &lt;ul&gt; {% endifchanged %} &lt;li&gt;{{forloop.counter}}. {{ article.headline }}&lt;/li&gt; {% if forloop.last %}&lt;/ul&gt;{% endif %} {% endfor %} </code></pre>
1
2008-12-11T12:33:33Z
[ "python", "django", "django-templates" ]
Filter a Python list by predicate
290,424
<p>I would want to do something like:</p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3, 4, 5] &gt;&gt;&gt; lst.find(lambda x: x % 2 == 0) 2 &gt;&gt;&gt; lst.findall(lambda x: x % 2 == 0) [2, 4] </code></pre> <p>Is there anything nearing such behavior in Python's standard libraries?</p> <p>I know it's very easy to roll-your-own here, but I'm looking for a more standard way.</p>
22
2008-11-14T15:30:00Z
290,440
<p>You can use the filter method:</p> <pre><code> >>> lst = [1, 2, 3, 4, 5] >>> filter(lambda x: x % 2 == 0, lst) [2, 4] </code></pre> <p>or a list comprehension:</p> <pre><code> >>> lst = [1, 2, 3, 4, 5] >>> [x for x in lst if x %2 == 0] [2, 4] </code></pre> <p>EDIT: for find (single element), you could try:</p> <pre><code> >>> (x for x in lst if x % 2 == 0).next() 2 </code></pre> <p>Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch. The () brackets make this a generator expression rather than a list comprehension.</p> <p>Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).</p> <p>These raise an exception if nothing is found</p> <pre><code>filter(lambda x: x % 2 == 0, lst)[0] [x for x in lst if x %2 == 0][0] </code></pre> <p>These return empty lists</p> <pre><code>filter(lambda x: x % 2 == 0, lst)[:1] [x for x in lst if x %2 == 0][:1] </code></pre>
38
2008-11-14T15:35:45Z
[ "python" ]
Using python to build web applications
290,456
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">two</a> <a href="http://stackoverflow.com/questions/271488/linking-languages">questions</a> I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++.</p> <p>That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me. </p> <p>I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates <em>be</em> the code as with php?</p> <p>I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php?</p>
8
2008-11-14T15:38:56Z
290,547
<p>Python is a good choice. </p> <p>I would avoid the CGI model though - you'll pay a large penalty for the interpreter launch on each request. Most Python web frameworks support <a href="http://www.wsgi.org/wsgi/" rel="nofollow">the WSGI standard</a> and can be hooked up to servers in a myriad of ways, but most live in some sort of long-running process that the web server communicates with (via proxying, FastCGI, SCGI, etc).</p> <p>Speaking of frameworks, the Python landscape is ripe with them. This is both good and bad. There are many fine options but it can be daunting to a newcomer.</p> <p>If you are looking for something that comes prepackaged with web/DB/templating integration I'd suggest looking at <a href="http://www.djangoproject.com" rel="nofollow">Django</a>, <a href="http://www.turbogears.org" rel="nofollow">TurboGears</a> or <a href="http://www.pylonshq.com" rel="nofollow">Pylons</a>. If you want to have more control over the individual components, look at <a href="http://www.cherrypy.org" rel="nofollow">CherryPy</a>, <a href="http://wsgiarea.pocoo.org/colubrid/" rel="nofollow">Colubrid</a> or <a href="http://www.webpy.org" rel="nofollow">web.py</a>.</p> <p>As for whether or not it is as "easy as PHP", that is subjective. Usually it is encouraged to keep your templates and application logic separate in the Python web programming world, which can make your <em>life</em> easier. On the other hand, being able to write all of the code for a page in a PHP file is another definition of "easy".</p> <p>Good luck.</p>
17
2008-11-14T15:59:24Z
[ "python", "cgi" ]
Using python to build web applications
290,456
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">two</a> <a href="http://stackoverflow.com/questions/271488/linking-languages">questions</a> I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++.</p> <p>That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me. </p> <p>I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates <em>be</em> the code as with php?</p> <p>I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php?</p>
8
2008-11-14T15:38:56Z
290,577
<p>I would suggest <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, but given that you ask for something <em>"as easy as it is with php"</em> then you must take a look at PSP (<a href="http://www.modpython.org/live/current/doc-html/pyapi-psp.html" rel="nofollow">Python Server Pages</a>). While Django is a complete framework for doing websites, PSP can be used in the same way than PHP, without any framework.</p>
5
2008-11-14T16:08:08Z
[ "python", "cgi" ]
Using python to build web applications
290,456
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">two</a> <a href="http://stackoverflow.com/questions/271488/linking-languages">questions</a> I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++.</p> <p>That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me. </p> <p>I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates <em>be</em> the code as with php?</p> <p>I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php?</p>
8
2008-11-14T15:38:56Z
290,609
<p>It is easier to write web-apps in python than it's in php. Particularly because python is not a broken language.</p> <p>Pick up some web framework that supports mod_wsgi or roll out your own. WSGI apps are really easy to deploy after you get a hold from doing it.</p> <p>If you want templates then genshi is about the best templating engine I've found for python and you can use it however you like.</p>
3
2008-11-14T16:17:29Z
[ "python", "cgi" ]
Using python to build web applications
290,456
<p>This is a follow-up to <a href="http://stackoverflow.com/questions/269417/which-language-should-i-use">two</a> <a href="http://stackoverflow.com/questions/271488/linking-languages">questions</a> I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++.</p> <p>That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me. </p> <p>I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates <em>be</em> the code as with php?</p> <p>I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php?</p>
8
2008-11-14T15:38:56Z
290,650
<p>"how easy is CGI programming in python?" Easier than C, that's for sure. Python is easier because -- simply -- it's an easier language to work with than C. First and foremost: no memory allocation-deallocation. Beyond that, the OO programming model is excellent.</p> <p>Beyond the essential language simplicity, the Python <a href="http://www.wsgi.org/wsgi/">WSGI</a> standard is much easier to cope with than the CGI standard.</p> <p>However, raw CGI is a huge pain when compared with the greatly simplified world of an all-Python framework (<a href="http://turbogears.org/">TurboGears</a>, <a href="http://www.cherrypy.org/">CherryPy</a>, <a href="http://www.djangoproject.com/">Django</a>, whatever.)</p> <p>The frameworks impose a lot of (necessary) structure. The out-of-the-box experience for a CGI programmer is that it's too much to learn. True. All new things are too much to learn. However, the value far exceeds the investment.</p> <p>With Django, you're up and running within minutes. Seriously. <code>django-admin.py startproject</code> and you have something you can run almost immediately. You do have to design your URL's, write view functions and design page templates. All of which is work. But it's <em>less</em> work than CGI in C. </p> <p>Django has a better architecture than PHP because the presentation templates are completely separated from the processing. This leads to some confusion (see <a href="http://stackoverflow.com/questions/276345/syntax-error-whenever-i-put-python-code-inside-a-django-template">Syntax error whenever I put python code inside a django template</a>) when you want to use the free-and-unconstrained PHP style on the Django framework.</p> <p><strong>linking the user interface to the back-end</strong></p> <p>Python front-end (Django, for example) uses Python view functions. Those view functions can contain any Python code at all. That includes, if necessary, modules written in C and callable from Python.</p> <p>That means you can compile a <a href="http://clipsrules.sourceforge.net/">CLIPS</a> module with a Python-friendly interface. It becomes something available to your Python code with the <code>import</code> statement.</p> <p>Sometimes, however, that's ineffective because your Django pages are waiting for the CLIPS engine to finish. An alternative is to use something like a named pipe.</p> <p>You have your CLIPS-based app, written entirely in C, reading from a named pipe. Your Django application, written entirely in Python, writes to that named pipe. Since you've got two independent processes, you'll max out all of your cores pretty quickly like this.</p>
8
2008-11-14T16:28:03Z
[ "python", "cgi" ]
Django Forms - How to Not Validate?
290,896
<p>Say I have this simple form:</p> <pre><code>class ContactForm(forms.Form): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) </code></pre> <p>And I have a default value for one field but not the other. So I set it up like this:</p> <pre><code>default_data = {'first_name','greg'} form1=ContactForm(default_data) </code></pre> <p>However now when I go to display it, Django shows a validation error saying last_name is required:</p> <pre><code>print form1.as_table() </code></pre> <p>What is the correct way to do this? Since this isn't data the user has submitted, just data I want to prefill.</p> <p><strong>Note:</strong> required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.</p>
6
2008-11-14T18:04:27Z
290,910
<p>From the django docs is this:</p> <pre><code>from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField() cc_myself = forms.BooleanField(required=False) </code></pre> <p>The "required=False" should produce the effect you're after.</p>
0
2008-11-14T18:10:27Z
[ "python", "django", "forms" ]
Django Forms - How to Not Validate?
290,896
<p>Say I have this simple form:</p> <pre><code>class ContactForm(forms.Form): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) </code></pre> <p>And I have a default value for one field but not the other. So I set it up like this:</p> <pre><code>default_data = {'first_name','greg'} form1=ContactForm(default_data) </code></pre> <p>However now when I go to display it, Django shows a validation error saying last_name is required:</p> <pre><code>print form1.as_table() </code></pre> <p>What is the correct way to do this? Since this isn't data the user has submitted, just data I want to prefill.</p> <p><strong>Note:</strong> required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.</p>
6
2008-11-14T18:04:27Z
290,962
<p>Form constructor has <code>initial</code> param that allows to provide default values for fields.</p>
10
2008-11-14T18:32:12Z
[ "python", "django", "forms" ]
Django Forms - How to Not Validate?
290,896
<p>Say I have this simple form:</p> <pre><code>class ContactForm(forms.Form): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) </code></pre> <p>And I have a default value for one field but not the other. So I set it up like this:</p> <pre><code>default_data = {'first_name','greg'} form1=ContactForm(default_data) </code></pre> <p>However now when I go to display it, Django shows a validation error saying last_name is required:</p> <pre><code>print form1.as_table() </code></pre> <p>What is the correct way to do this? Since this isn't data the user has submitted, just data I want to prefill.</p> <p><strong>Note:</strong> required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.</p>
6
2008-11-14T18:04:27Z
39,913,942
<p>Also it's possible manually validate and clear errors later: <code>form.errors.clear()</code></p>
1
2016-10-07T09:29:19Z
[ "python", "django", "forms" ]
Is it possible for a running python program to overwrite itself?
291,448
<p>Is it possible for a python script to open its own source file and overwrite it?</p> <p>The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.</p>
16
2008-11-14T21:11:57Z
291,470
<p>That's certainly possible. After the script is loaded/imported, the Python interpreter won't access it anymore, except when printing source line in a exception stack trace. Any pyc file will be regenerated the next time as the source file is newer than the pyc.</p>
21
2008-11-14T21:16:35Z
[ "python" ]
Is it possible for a running python program to overwrite itself?
291,448
<p>Is it possible for a python script to open its own source file and overwrite it?</p> <p>The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.</p>
16
2008-11-14T21:11:57Z
291,650
<p>Actually, it's preferable that your application starts with a dummy checker-downloader that changes rarely (if ever); before running, it should check if any updates are available; if yes, then it would download them (typically the rest of the app would be modules) and then import them and start the app.</p> <p>This way, as soon as updates are available, you start the application and will run the latest version; otherwise, a restart of the application is required.</p>
8
2008-11-14T22:28:50Z
[ "python" ]
Is it possible for a running python program to overwrite itself?
291,448
<p>Is it possible for a python script to open its own source file and overwrite it?</p> <p>The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.</p>
16
2008-11-14T21:11:57Z
291,733
<p>If you put most of the code into a module, you could have the main file (which is the one that is run) check the update location, and automatically download the most recent version and install that, before the module is imported.</p> <p>That way you wouldn't have to have a restart of the application to run the most recent version, just reimport the module. </p> <pre><code># Check version of module import module # Check update address if update_version &gt; module.version: download(update_module) import module reload(module) module.main() </code></pre> <p>You can use the reload() function to force a module to reload it's data. Note there are some caveats to this: objects created using classes in this module will not be magically updated to the new version, and "from module import stuff" before the reimport may result in "stuff" referring to the old object "module.stuff".</p> <p>[Clearly, I didn't read the previous post clearly enough - it does exactly what I suggest!]</p>
10
2008-11-14T23:06:10Z
[ "python" ]
Is it possible for a running python program to overwrite itself?
291,448
<p>Is it possible for a python script to open its own source file and overwrite it?</p> <p>The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.</p>
16
2008-11-14T21:11:57Z
514,505
<p>You might also want to check out this module ( which is in 2.5 &amp; 3 as well )</p> <p><a href="http://www.python.org/doc/2.1.3/lib/os-process.html" rel="nofollow">http://www.python.org/doc/2.1.3/lib/os-process.html</a></p> <p>Specifically the execv method will overwrite the current process with whatever you call from this method. I've done some personnel tests and it works pretty reliably.</p>
1
2009-02-05T04:01:03Z
[ "python" ]
Search directory in SVN for files with specific file extension and copy to another folder?
291,467
<p>I would like my python script to search through a directory in SVN, locate the files ending with a particular extension (eg. *.exe), and copy these files to a directory that has been created in my C drive. How can I do this? I'm new to Python so a detailed response and/or point in the right direction would be very much appreciated. </p> <p><em>Follow-up:</em> When using os.walk what parameter would I pass in to ensure that I'm copying files with a specific extension (eg. *.exe)?</p>
1
2008-11-14T21:16:14Z
291,477
<p>I think it is easiest to check out (or, better, export) the source tree using the svn command line utility: you can use os.system to invoke it. There are also direct Python-to-svn API bindings, but I would advise against using them if you are new to Python.</p> <p>You can then traverse the checkout folder, e.g. using os.walk; the copying itself can be done with shutil.copy.</p>
1
2008-11-14T21:19:22Z
[ "python", "svn", "file" ]
Python exception backtrace tells me where line ends, where does it begin?
291,508
<p>When A Python exception is thrown by code that spans multiple lines, e.g.:</p> <pre><code> myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] </code></pre> <p>Python will report the line number of the last line, and will show the code fragment from that line:</p> <pre><code>Traceback (most recent call last): File "test.py", line 4, in &lt;module&gt; i) for i in range(10)] NameError: name 'foo' is not defined </code></pre> <p>Is there any way to determine what the first line is? Is there any way to catch the exception and manipulate the <a href="http://docs.python.org/library/traceback.html" rel="nofollow">traceback</a> object to be able to report something like this instead:</p> <pre><code>Traceback (most recent call last): File "test.py", lines 1-4 in &lt;module&gt; myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] NameError: name 'foo' is not defined </code></pre>
1
2008-11-14T21:31:10Z
291,579
<p>In a try/except block you can except NameError and try setting NameError.lineno, though I'm not exactly sure if or how this works, but it's the best I've found thusfar.</p> <pre><code>try: somecode except NameError NameError.lineno = [1,4] </code></pre> <p>You'll have to figure out where the statement begins and ends yourself somehow as well as which statement is raising the error.</p> <p>Hope this helps</p>
0
2008-11-14T21:59:29Z
[ "python", "exception" ]
Python exception backtrace tells me where line ends, where does it begin?
291,508
<p>When A Python exception is thrown by code that spans multiple lines, e.g.:</p> <pre><code> myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] </code></pre> <p>Python will report the line number of the last line, and will show the code fragment from that line:</p> <pre><code>Traceback (most recent call last): File "test.py", line 4, in &lt;module&gt; i) for i in range(10)] NameError: name 'foo' is not defined </code></pre> <p>Is there any way to determine what the first line is? Is there any way to catch the exception and manipulate the <a href="http://docs.python.org/library/traceback.html" rel="nofollow">traceback</a> object to be able to report something like this instead:</p> <pre><code>Traceback (most recent call last): File "test.py", lines 1-4 in &lt;module&gt; myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] NameError: name 'foo' is not defined </code></pre>
1
2008-11-14T21:31:10Z
292,505
<p>Finding the beginning of the line will be really hard. You'll have to either parse the Python or maybe dig into the compiled byte code. There are modules in the standard library for parsing Python, but I can tell you from experience that interpreting their output is a black art. And I'm not sure the compiled byte code has the answer either...</p>
2
2008-11-15T12:50:51Z
[ "python", "exception" ]
How do I split a huge text file in python
291,740
<p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p> <p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p> <p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p> <p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
15
2008-11-14T23:12:14Z
291,759
<p>Check out <code>os.stat()</code> for file size and <code>file.readlines([sizehint])</code>. Those two functions should be all you need for the reading part, and hopefully you know how to do the writing :)</p>
13
2008-11-14T23:18:32Z
[ "python", "text-files" ]
How do I split a huge text file in python
291,740
<p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p> <p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p> <p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p> <p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
15
2008-11-14T23:12:14Z
291,838
<p>You can use <code>wc</code> and <code>split</code> (see the respective manpages) to get the desired effect. In <code>bash</code>:</p> <pre><code>split -dl$((`wc -l 'filename'|sed 's/ .*$//'` / 3 + 1)) filename filename-chunk. </code></pre> <p>produces 3 parts of the same linecount (with a rounding error in the last, of course), named <code>filename-chunk.00</code> to <code>filename-chunk.02</code>.</p>
3
2008-11-15T00:11:38Z
[ "python", "text-files" ]
How do I split a huge text file in python
291,740
<p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p> <p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p> <p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p> <p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
15
2008-11-14T23:12:14Z
292,848
<p>Or, a python version of wc and split:</p> <pre><code>lines = 0 for l in open(filename): lines += 1 </code></pre> <p>Then some code to read the first lines/3 into one file, the next lines/3 into another , etc.</p>
0
2008-11-15T18:05:32Z
[ "python", "text-files" ]
How do I split a huge text file in python
291,740
<p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p> <p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p> <p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p> <p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
15
2008-11-14T23:12:14Z
294,384
<p>I've written the program and it seems to work fine. So thanks to Kamil Kisiel for getting me started.<br /> (Note that FileSizeParts() is a function not shown here)<br /> Later I may get round to doing a version that does a binary read to see if its any quicker.</p> <pre><code>def Split(inputFile,numParts,outputName): fileSize=os.stat(inputFile).st_size parts=FileSizeParts(fileSize,numParts) openInputFile = open(inputFile, 'r') outPart=1 for part in parts: if openInputFile.tell()&lt;fileSize: fullOutputName=outputName+os.extsep+str(outPart) outPart+=1 openOutputFile=open(fullOutputName,'w') openOutputFile.writelines(openInputFile.readlines(part)) openOutputFile.close() openInputFile.close() return outPart-1 </code></pre>
3
2008-11-16T20:54:21Z
[ "python", "text-files" ]
How do I split a huge text file in python
291,740
<p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p> <p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p> <p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p> <p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
15
2008-11-14T23:12:14Z
2,203,797
<p>linux has a split command</p> <p>split -l 100000 file.txt</p> <p>would split into files of equal 100,000 line size</p>
25
2010-02-04T22:42:29Z
[ "python", "text-files" ]