title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 11,278,750 | 13 | 2012-07-01T00:41:40Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | note how well the `with` keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):
```
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")
``` |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 15,647,557 | 8 | 2013-03-26T21:15:20Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | <https://raw.github.com/fabric/fabric/master/fabric/colors.py>
```
"""
.. 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')
``` |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 17,064,509 | 18 | 2013-06-12T11:38:01Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | I have wrapped @joeld answer into a module with global functions that I can use anywhere in my code.
file: log.py
```
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
```
use as follows:
```
import log
log.info("Hello World")
log.err("System Error")
``` |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 18,786,263 | 16 | 2013-09-13T12:24:50Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | I use the colorama module for coloured terminal printing in Python. A link is here <http://pypi.python.org/pypi/colorama>
Some example code of printing red and green text:
```
from colorama import *
print(Fore.GREEN + 'Green text')
print(Fore.RED + 'Red text')
```
I used colorama to write a basic Matrix program
Installation on Ubuntu (your distribution install command may be different)
```
sudo apt-get install python-pip
sudo pip install colorama
``` |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 21,786,287 | 72 | 2014-02-14T17:56:38Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | Print a string that starts a color/style, then the string, then end the color/style change with `'\x1b[0m'`:
```
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
```
[](http://i.stack.imgur.com/RN3MN.png)
Get a table of format options for shell text with following 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()
```
# Light-on-dark example (complete)
[](http://i.stack.imgur.com/6otvY.png)
# Dark-on-light example (partial)
 |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 26,445,590 | 15 | 2014-10-18T23:26:05Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | 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:
```
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'
``` |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 28,388,343 | 9 | 2015-02-07T22:43:49Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | ## YAY! another version
while i find [this](http://stackoverflow.com/a/26445590/3191896) answer useful, i modified it a bit. this [Github Gist](https://gist.github.com/Jossef/0ee20314577925b4027f) is the result
**usage**
```
print colors.draw("i'm yellow", bold=True, fg_yellow=True)
```

in addition you can wrap common usages:
```
print colors.error('sorry, ')
```

### <https://gist.github.com/Jossef/0ee20314577925b4027f> |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 29,723,536 | 17 | 2015-04-18T22:18:35Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | Stupidly simple based on @joeld's answer
```
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)
```
Then just
```
PrintInColor.red('hello', end=' ')
PrintInColor.green('world')
``` |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 30,564,892 | 15 | 2015-06-01T02:36:18Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | uses ANSI
```
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'
```
Make your function :-
```
def red(name):
print ("\033[91m {}\033[00m" .format(name))
```
Call function :-
> red("Good one")
> Good one <-- It will print in Red ,
Note :- not required any module |
Print in terminal with colors using Python? | 287,871 | 1,024 | 2008-11-13T18:58:10Z | 34,443,116 | 21 | 2015-12-23T20:20:49Z | [
"python",
"unicode",
"terminal",
"ansi-colors"
] | How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block? | Try this simple 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")
``` |
Connect to Exchange mailbox with Python | 288,546 | 11 | 2008-11-13T22:19:01Z | 3,072,491 | 25 | 2010-06-18T19:21:29Z | [
"python",
"email",
"connection",
"exchange-server",
"pywin32"
] | 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 & password.
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.
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!
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). | I know this is an old thread, but...
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.
<http://msdn.microsoft.com/en-us/library/bb204119.aspx>
UPDATE: I have released a [Python EWS client](https://pypi.python.org/pypi/exchangelib/) on PyPI that supports autodiscover, calendars, inbox, tasks and contacts |
Connect to Exchange mailbox with Python | 288,546 | 11 | 2008-11-13T22:19:01Z | 24,020,665 | 14 | 2014-06-03T16:48:07Z | [
"python",
"email",
"connection",
"exchange-server",
"pywin32"
] | 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 & password.
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.
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!
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). | Ive got it, to connect to outbound exchange you need to connect like this:
```
import smtplib
url = YOUR_EXCHANGE_SERVER
conn = smtplib.SMTP(url,587)
conn.starttls()
user,password = (EXCHANGE_USER,EXCHANGE_PASSWORD)
conn.login(user,password)
```
now you can send like a normal connection
```
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))
```
to get the mail from your inbox its a little different
```
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()
```
this gives you a list of message id'
s that you can use to get your emails
```
latest_email_id = msg_id_list[-1]
result,data = conn.fetch(latest_email_id,"(RFC822)")
raw_email = data[0][1]
```
now raw\_email is your email messsage, but its not very pretty, if you want to parse it do somthing like this
```
from email.parser import Parser
p = Parser()
msg = p.parsestr(raw_email)
```
now you can do
```
msg.get('From')
msg.get('Subject')
```
or for the content
```
msg.get_payload()
```
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
```
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
```
now
```
msg_contant = process_multipart_message(msg)
```
will give you the whole message every time. |
Is it correct to inherit from built-in classes? | 288,695 | 6 | 2008-11-13T23:06:05Z | 288,807 | 15 | 2008-11-13T23:53:29Z | [
"python",
"inheritance",
"oop"
] | I want to parse an Apache **access.log** 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.
I am going to create a class **ApacheAccessLog**, and the only thing I can imagine now, it will be doing is '**readline**' method. Is it conventionally correct to inherit from the builtin **file** class in this case, so the class will behave just like an instance of the **file** class itself, or not? What is the best way of doing that? | In this case I would use *delegation* rather than *inheritance*. It means that your class should contain the file object as an attribute and invoke a `readline` method on it. You could pass a file object in the constructor of the logger class.
There are at least two reasons for this:
1. Delegation reduces coupling, for example in place of file objects you can use any other object that implements a `readline` method (*duck typing* comes handy here).
2. 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. |
Can I use named groups in a Perl regex to get the results in a hash? | 288,968 | 14 | 2008-11-14T01:28:40Z | 288,989 | 31 | 2008-11-14T01:40:02Z | [
"python",
"regex",
"perl"
] | Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the `$n` values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.
Python does it like so:
```
>>> import re
>>> regex = re.compile(r'(?P<count>\d+)')
>>> match = regex.match('42')
>>> print match.groupdict()
{'count': '42'}
```
I know the `?P` 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? | Perl uses `(?<NAME>pattern)` to specify names captures. You have to use the `%+` hash to retrieve them.
```
$variable =~ /(?<count>\d+)/;
print "Count is $+{count}";
```
This is only supported on Perl 5.10 and higher though. |
Can I use named groups in a Perl regex to get the results in a hash? | 288,968 | 14 | 2008-11-14T01:28:40Z | 289,149 | 16 | 2008-11-14T03:14:48Z | [
"python",
"regex",
"perl"
] | Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the `$n` values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.
Python does it like so:
```
>>> import re
>>> regex = re.compile(r'(?P<count>\d+)')
>>> match = regex.match('42')
>>> print match.groupdict()
{'count': '42'}
```
I know the `?P` 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? | As of Perl 5.10, Perl regexes support [some Python features](http://perldoc.perl.org/perlre.html#PCRE%2fPython-Support), making them *Python* compatible regexes, I guess. The Python versions have the "P" in them, but all of these work in Perl 5.10. See the [perlre](http://perldoc.perl.org/perlre.html) documentation for the details:
Define a named capture buffer. Equivalent to `(?<NAME>pattern)`.
```
(?P<NAME>pattern)
```
Backreference to a named capture buffer. Equivalent to `\g{NAME}`.
```
(?P=NAME)
```
Subroutine call to a named capture buffer. Equivalent to `(?&NAME)`.
```
(?P>NAME)
```
Although I didn't add the Python-compatibility to the latest edition of [Learning Perl](http://oreilly.com/catalog/9780596520106/), we do cover the new Perl 5.10 features, including named captures. |
Can I use named groups in a Perl regex to get the results in a hash? | 288,968 | 14 | 2008-11-14T01:28:40Z | 1,091,618 | 8 | 2009-07-07T10:44:31Z | [
"python",
"regex",
"perl"
] | Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the `$n` values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.
Python does it like so:
```
>>> import re
>>> regex = re.compile(r'(?P<count>\d+)')
>>> match = regex.match('42')
>>> print match.groupdict()
{'count': '42'}
```
I know the `?P` 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? | As couple of people said perl 5.10 has named groups.
But in previous perls you can do something, not as convenient, but relatively nice:
```
my %hash;
@hash{"count", "something_else"} = $string =~ /(\d+)\s*,\s*(\S+)/;
```
and then you can use:
$hash{"count"} and $hash{"something\_else"}. |
receiving data over a python socket | 289,035 | 4 | 2008-11-14T02:04:45Z | 289,046 | 15 | 2008-11-14T02:10:28Z | [
"python",
"sockets"
] | 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
All the examples on the web are of tcp clients where they have
```
while 1:
data = sock.recv(1024)
```
But this creates a look to infinite loop to receive data via the socket, does it not?
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
Thanks | You've probably missed a very important part of those [examples](http://docs.python.org/library/socket.html#example) - the lines that follow the "recv()" call:
```
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
``` |
What's the simplest way to access mssql with python or ironpython? | 289,978 | 21 | 2008-11-14T12:50:11Z | 290,009 | 16 | 2008-11-14T13:02:21Z | [
"python",
"sql-server",
"ironpython"
] | 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.
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. | I use [SQL Alchemy](http://www.sqlalchemy.org/) 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 [Elixir](http://elixir.ematia.de/trac/wiki), which is a thin layer on top of SQL Alchemy. To use either one of those, you'll need [pyodbc](http://pyodbc.sourceforge.net/), but that's a pretty simple install.
Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc. |
What's the simplest way to access mssql with python or ironpython? | 289,978 | 21 | 2008-11-14T12:50:11Z | 291,473 | 11 | 2008-11-14T21:17:14Z | [
"python",
"sql-server",
"ironpython"
] | 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.
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. | pyodbc comes with Activestate Python, which can be downloaded from [here](http://www.activestate.com/store/productdetail.aspx?prdGuid=b08b04e0-6872-4d9d-a722-7a0c2dea2758). A minimal odbc script to connect to a SQL Server 2005 database looks like this:
```
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]
``` |
What's the simplest way to access mssql with python or ironpython? | 289,978 | 21 | 2008-11-14T12:50:11Z | 301,746 | 23 | 2008-11-19T12:27:37Z | [
"python",
"sql-server",
"ironpython"
] | 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.
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. | 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:
```
import clr
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection, SqlParameter
conn_string = 'data source=<machine>; initial catalog=<database>; 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()
```
If you've already got IronPython, you don't need to install anything else.
Lots of docs available [here](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx) and [here](http://www.ironpython.info/index.php/Contents#Databases). |
Filter a Python list by predicate | 290,424 | 22 | 2008-11-14T15:30:00Z | 290,440 | 38 | 2008-11-14T15:35:45Z | [
"python"
] | I would want to do something like:
```
>>> lst = [1, 2, 3, 4, 5]
>>> lst.find(lambda x: x % 2 == 0)
2
>>> lst.findall(lambda x: x % 2 == 0)
[2, 4]
```
Is there anything nearing such behavior in Python's standard libraries?
I know it's very easy to roll-your-own here, but I'm looking for a more standard way. | You can use the filter method:
```
>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda x: x % 2 == 0, lst)
[2, 4]
```
or a list comprehension:
```
>>> lst = [1, 2, 3, 4, 5]
>>> [x for x in lst if x %2 == 0]
[2, 4]
```
EDIT: for find (single element), you could try:
```
>>> (x for x in lst if x % 2 == 0).next()
2
```
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.
Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).
These raise an exception if nothing is found
```
filter(lambda x: x % 2 == 0, lst)[0]
[x for x in lst if x %2 == 0][0]
```
These return empty lists
```
filter(lambda x: x % 2 == 0, lst)[:1]
[x for x in lst if x %2 == 0][:1]
``` |
Using python to build web applications | 290,456 | 8 | 2008-11-14T15:38:56Z | 290,547 | 17 | 2008-11-14T15:59:24Z | [
"python",
"cgi"
] | This is a follow-up to [two](http://stackoverflow.com/questions/269417/which-language-should-i-use) [questions](http://stackoverflow.com/questions/271488/linking-languages) 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++.
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.
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 *be* the code as with php?
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? | Python is a good choice.
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 [the WSGI standard](http://www.wsgi.org/wsgi/) 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).
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.
If you are looking for something that comes prepackaged with web/DB/templating integration I'd suggest looking at [Django](http://www.djangoproject.com), [TurboGears](http://www.turbogears.org) or [Pylons](http://www.pylonshq.com). If you want to have more control over the individual components, look at [CherryPy](http://www.cherrypy.org), [Colubrid](http://wsgiarea.pocoo.org/colubrid/) or [web.py](http://www.webpy.org).
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 *life* 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".
Good luck. |
Using python to build web applications | 290,456 | 8 | 2008-11-14T15:38:56Z | 290,650 | 8 | 2008-11-14T16:28:03Z | [
"python",
"cgi"
] | This is a follow-up to [two](http://stackoverflow.com/questions/269417/which-language-should-i-use) [questions](http://stackoverflow.com/questions/271488/linking-languages) 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++.
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.
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 *be* the code as with php?
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? | "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.
Beyond the essential language simplicity, the Python [WSGI](http://www.wsgi.org/wsgi/) standard is much easier to cope with than the CGI standard.
However, raw CGI is a huge pain when compared with the greatly simplified world of an all-Python framework ([TurboGears](http://turbogears.org/), [CherryPy](http://www.cherrypy.org/), [Django](http://www.djangoproject.com/), whatever.)
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.
With Django, you're up and running within minutes. Seriously. `django-admin.py startproject` 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 *less* work than CGI in C.
Django has a better architecture than PHP because the presentation templates are completely separated from the processing. This leads to some confusion (see [Syntax error whenever I put python code inside a django template](http://stackoverflow.com/questions/276345/syntax-error-whenever-i-put-python-code-inside-a-django-template)) when you want to use the free-and-unconstrained PHP style on the Django framework.
**linking the user interface to the back-end**
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.
That means you can compile a [CLIPS](http://clipsrules.sourceforge.net/) module with a Python-friendly interface. It becomes something available to your Python code with the `import` statement.
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.
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. |
Django Forms - How to Not Validate? | 290,896 | 6 | 2008-11-14T18:04:27Z | 290,962 | 10 | 2008-11-14T18:32:12Z | [
"python",
"django",
"forms"
] | Say I have this simple form:
```
class ContactForm(forms.Form):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
```
And I have a default value for one field but not the other. So I set it up like this:
```
default_data = {'first_name','greg'}
form1=ContactForm(default_data)
```
However now when I go to display it, Django shows a validation error saying last\_name is required:
```
print form1.as_table()
```
What is the correct way to do this? Since this isn't data the user has submitted, just data I want to prefill.
**Note:** 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. | Form constructor has `initial` param that allows to provide default values for fields. |
Is it possible for a running python program to overwrite itself? | 291,448 | 16 | 2008-11-14T21:11:57Z | 291,470 | 21 | 2008-11-14T21:16:35Z | [
"python"
] | Is it possible for a python script to open its own source file and overwrite it?
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. | 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. |
Is it possible for a running python program to overwrite itself? | 291,448 | 16 | 2008-11-14T21:11:57Z | 291,650 | 8 | 2008-11-14T22:28:50Z | [
"python"
] | Is it possible for a python script to open its own source file and overwrite it?
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. | 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.
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. |
Is it possible for a running python program to overwrite itself? | 291,448 | 16 | 2008-11-14T21:11:57Z | 291,733 | 10 | 2008-11-14T23:06:10Z | [
"python"
] | Is it possible for a python script to open its own source file and overwrite it?
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. | 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.
That way you wouldn't have to have a restart of the application to run the most recent version, just reimport the module.
```
# Check version of module
import module
# Check update address
if update_version > module.version:
download(update_module)
import module
reload(module)
module.main()
```
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".
[Clearly, I didn't read the previous post clearly enough - it does exactly what I suggest!] |
How do I split a huge text file in python | 291,740 | 15 | 2008-11-14T23:12:14Z | 291,759 | 13 | 2008-11-14T23:18:32Z | [
"python",
"text-files"
] | 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.
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 *filename*.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.
Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?
I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-) | Check out `os.stat()` for file size and `file.readlines([sizehint])`. Those two functions should be all you need for the reading part, and hopefully you know how to do the writing :) |
How do I split a huge text file in python | 291,740 | 15 | 2008-11-14T23:12:14Z | 2,203,797 | 25 | 2010-02-04T22:42:29Z | [
"python",
"text-files"
] | 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.
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 *filename*.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.
Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?
I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-) | linux has a split command
split -l 100000 file.txt
would split into files of equal 100,000 line size |
How do I split a huge text file in python | 291,740 | 15 | 2008-11-14T23:12:14Z | 10,599,406 | 7 | 2012-05-15T11:04:13Z | [
"python",
"text-files"
] | 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.
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 *filename*.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.
Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?
I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-) | As an alternative method, using the logging library:
```
>>> import logging.handlers
>>> log = logging.getLogger()
>>> fh = logging.handlers.RotatingFileHandler("D://filename.txt",
maxBytes=2**20*100, backupCount=100)
# 100 MB each, up to a maximum of 100 files
>>> log.addHandler(fh)
>>> log.setLevel(logging.INFO)
>>> f = open("D://biglog.txt")
>>> while True:
... log.info(f.readline().strip())
```
Your files will appear as follows:
> filename.txt (end of file)
> filename.txt.1
> filename.txt.2
> ...
> filename.txt.10 (start of file)
This is a quick and easy way to make a huge log file match your `RotatingFileHandler` implementation. |
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | 152 | 2008-11-15T01:21:33Z | 291,968 | 164 | 2008-11-15T01:39:26Z | [
"python",
"django",
"django-forms"
] | Say I have the following in my `models.py`:
```
class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
```
I.e. there are multiple `Companies`, each having a range of `Rates` and `Clients`. Each `Client` should have a base `Rate` that is chosen from it's parent `Company's Rates`, not another `Company's Rates`.
When creating a form for adding a `Client`, I would like to remove the `Company` choices (as that has already been selected via an "Add Client" button on the `Company` page) and limit the `Rate` choices to that `Company` as well.
How do I go about this in Django 1.0?
My current `forms.py` file is just boilerplate at the moment:
```
from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
```
And the `views.py` is also basic:
```
from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
```
In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:
```
manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
```
[`ForeignKey.limit_choices_to`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) seems promising but I don't know how to pass in `the_company.id` and I'm not clear if that will work outside the Admin interface anyway.
Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.) | ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for [ModelChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield).
So, provide a QuerySet to the field's `queryset` attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.
```
form.rate.queryset = Rate.objects.filter(company_id=the_company.id)
```
If you take the default ModelForm object, `form.fields["rate"].queryset = ...`
This is done explicitly in the view. No hacking around. |
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | 152 | 2008-11-15T01:21:33Z | 1,244,586 | 100 | 2009-08-07T13:01:38Z | [
"python",
"django",
"django-forms"
] | Say I have the following in my `models.py`:
```
class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
```
I.e. there are multiple `Companies`, each having a range of `Rates` and `Clients`. Each `Client` should have a base `Rate` that is chosen from it's parent `Company's Rates`, not another `Company's Rates`.
When creating a form for adding a `Client`, I would like to remove the `Company` choices (as that has already been selected via an "Add Client" button on the `Company` page) and limit the `Rate` choices to that `Company` as well.
How do I go about this in Django 1.0?
My current `forms.py` file is just boilerplate at the moment:
```
from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
```
And the `views.py` is also basic:
```
from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
```
In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:
```
manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
```
[`ForeignKey.limit_choices_to`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) seems promising but I don't know how to pass in `the_company.id` and I'm not clear if that will work outside the Admin interface anyway.
Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.) | In addition to S.Lott's answer and as becomingGuru mentioned in comments, its possible to add the queryset filters by overriding the `ModelForm.__init__` function. (This could easily apply to regular forms) it can help with reuse and keeps the view function tidy.
```
class ClientForm(forms.ModelForm):
def __init__(self,company,*args,**kwargs):
super (ClientForm,self ).__init__(*args,**kwargs) # populates the post
self.fields['rate'].queryset = Rate.objects.filter(company=company)
self.fields['client'].queryset = Client.objects.filter(company=company)
class Meta:
model = Client
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(the_company,request.POST) #<-- Note the extra arg
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm(the_company)
return render_to_response('addclient.html',
{'form': form, 'the_company':the_company})
```
This can be useful for reuse say if you have common filters needed on many models (normally I declare an abstract Form class). E.g.
```
class UberClientForm(ClientForm):
class Meta:
model = UberClient
def view(request):
...
form = UberClientForm(company)
...
#or even extend the existing custom init
class PITAClient(ClientForm):
def __init__(company, *args, **args):
super (PITAClient,self ).__init__(company,*args,**kwargs)
self.fields['support_staff'].queryset = User.objects.exclude(user='michael')
```
Other than that I'm just restating Django blog material of which there are many good ones out there. |
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | 152 | 2008-11-15T01:21:33Z | 10,159,363 | 12 | 2012-04-15T03:53:42Z | [
"python",
"django",
"django-forms"
] | Say I have the following in my `models.py`:
```
class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
```
I.e. there are multiple `Companies`, each having a range of `Rates` and `Clients`. Each `Client` should have a base `Rate` that is chosen from it's parent `Company's Rates`, not another `Company's Rates`.
When creating a form for adding a `Client`, I would like to remove the `Company` choices (as that has already been selected via an "Add Client" button on the `Company` page) and limit the `Rate` choices to that `Company` as well.
How do I go about this in Django 1.0?
My current `forms.py` file is just boilerplate at the moment:
```
from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
```
And the `views.py` is also basic:
```
from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
```
In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:
```
manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
```
[`ForeignKey.limit_choices_to`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) seems promising but I don't know how to pass in `the_company.id` and I'm not clear if that will work outside the Admin interface anyway.
Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.) | To do this with a generic view, like CreateView...
```
class AddPhotoToProject(CreateView):
"""
a view where a user can associate a photo with a project
"""
model = Connection
form_class = CreateConnectionForm
def get_context_data(self, **kwargs):
context = super(AddPhotoToProject, self).get_context_data(**kwargs)
context['photo'] = self.kwargs['pk']
context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
return context
def form_valid(self, form):
pobj = Photo.objects.get(pk=self.kwargs['pk'])
obj = form.save(commit=False)
obj.photo = pobj
obj.save()
return_json = {'success': True}
if self.request.is_ajax():
final_response = json.dumps(return_json)
return HttpResponse(final_response)
else:
messages.success(self.request, 'photo was added to project!')
return HttpResponseRedirect(reverse('MyPhotos'))
```
the most important part of that...
```
context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
```
, [read my post here](http://gravitymad.com/blog/2012/4/14/how-filter-django-forms-multiple-choice-or-foreign/) |
How do I filter ForeignKey choices in a Django ModelForm? | 291,945 | 152 | 2008-11-15T01:21:33Z | 15,667,564 | 31 | 2013-03-27T19:18:52Z | [
"python",
"django",
"django-forms"
] | Say I have the following in my `models.py`:
```
class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
```
I.e. there are multiple `Companies`, each having a range of `Rates` and `Clients`. Each `Client` should have a base `Rate` that is chosen from it's parent `Company's Rates`, not another `Company's Rates`.
When creating a form for adding a `Client`, I would like to remove the `Company` choices (as that has already been selected via an "Add Client" button on the `Company` page) and limit the `Rate` choices to that `Company` as well.
How do I go about this in Django 1.0?
My current `forms.py` file is just boilerplate at the moment:
```
from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
```
And the `views.py` is also basic:
```
from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
```
In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:
```
manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
```
[`ForeignKey.limit_choices_to`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) seems promising but I don't know how to pass in `the_company.id` and I'm not clear if that will work outside the Admin interface anyway.
Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.) | This is simple, and works with Django 1.4:
```
class ClientAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ClientAdminForm, self).__init__(*args, **kwargs)
# access object through self.instance...
self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)
class ClientAdmin(admin.ModelAdmin):
form = ClientAdminForm
....
```
You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):
```
ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to
override the default formfield for a foreign keys field. For example,
to return a subset of objects for this foreign key field based on the
user:'''
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
```
An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.
I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site.
The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration).
The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset.
In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above.
```
class FrontEndAdmin(models.ModelAdmin):
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(FrontEndAdmin, self).__init__(model, admin_site)
```
remove 'delete' buttons:
```
def get_actions(self, request):
actions = super(FrontEndAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
```
prevents delete permission
```
def has_delete_permission(self, request, obj=None):
return False
```
filters objects that can be viewed on the admin site:
```
def get_queryset(self, request):
if request.user.is_superuser:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
return qs
else:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
if hasattr(self.model, âuserâ):
return qs.filter(user=request.user)
if hasattr(self.model, âporcupineâ):
return qs.filter(porcupine=request.user.porcupine)
else:
return qs
```
filters choices for all foreignkey fields on the admin site:
```
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.employee.is_superuser:
return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
else:
if hasattr(db_field.rel.to, 'user'):
kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
if hasattr(db_field.rel.to, 'porcupine'):
kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)
``` |
Short Description of Scoping Rules | 291,978 | 228 | 2008-11-15T01:48:37Z | 292,502 | 212 | 2008-11-15T12:47:22Z | [
"python",
"scope",
"dynamic-languages"
] | What **exactly** are the Python scoping rules?
If I have some code:
```
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
```
Where is *x* found? Some possible choices include the list above:
1. In the enclosing source file
2. In the class namespace
3. In the function definition
4. In the for loop index variable
5. Inside the for loop
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers. | Actually, a concise rule for Python Scope resolution, from [Learning Python, 3rd. Ed.](http://rads.stackoverflow.com/amzn/click/0596513984). (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply)
LEGB Rule.
**L**, Local â Names assigned in any way within a function (`def` or `lambda`)), and not declared global in that function.
**E**, Enclosing function locals â Name in the local scope of any and all enclosing functions (`def` or `lambda`), from inner to outer.
**G**, Global (module) â Names assigned at the top-level of a module file, or declared global in a `def` within the file.
**B**, Built-in (Python) â Names preassigned in the built-in names module : `open`,`range`,`SyntaxError`,...
So, in the case of
```
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
```
The for loop does not have its own namespace. In LEGB order, the scopes would be
L : local, in the current def.
E : Enclosed function, any enclosing functions (if def spam was in another def)
G : Global. Were there any declared globally in the module?
B : Any builtin x() in Python. |
Short Description of Scoping Rules | 291,978 | 228 | 2008-11-15T01:48:37Z | 292,907 | 17 | 2008-11-15T18:52:49Z | [
"python",
"scope",
"dynamic-languages"
] | What **exactly** are the Python scoping rules?
If I have some code:
```
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
```
Where is *x* found? Some possible choices include the list above:
1. In the enclosing source file
2. In the class namespace
3. In the function definition
4. In the for loop index variable
5. Inside the for loop
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers. | The scoping rules for Python 2.x have been outlined already in other answers. The only thing I would add is that in Python 3.0, there is also the concept of a non-local scope (indicated by the 'nonlocal' keyword). This allows you to access outer scopes directly, and opens up the ability to do some neat tricks, including lexical closures (without ugly hacks involving mutable objects).
EDIT: Here's the [PEP](http://www.python.org/dev/peps/pep-3104/) with more information on this. |
Short Description of Scoping Rules | 291,978 | 228 | 2008-11-15T01:48:37Z | 293,097 | 96 | 2008-11-15T21:51:09Z | [
"python",
"scope",
"dynamic-languages"
] | What **exactly** are the Python scoping rules?
If I have some code:
```
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
```
Where is *x* found? Some possible choices include the list above:
1. In the enclosing source file
2. In the class namespace
3. In the function definition
4. In the for loop index variable
5. Inside the for loop
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers. | Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class's namespace, but they are not directly accessible from within the methods (or nested classes) they contain.
In your example there are only 3 scopes where x will be searched in:
* spam's scope - containing everything defined in code3 and code5 (as well as code4, your loop variable)
* The global scope - containing everything defined in code1, as well as Foo (and whatever changes after it)
* The builtins namespace. A bit of a special case - this contains the various Python builtin functions and types such as len() and str(). Generally this shouldn't be modified by any user code, so expect it to contain the standard functions and nothing else.
More scopes only appear when you introduce a nested function (or lambda) into the picture.
These will behave pretty much as you'd expect however. The nested function can access everything in the local scope, as well as anything in the enclosing function's scope. eg.
```
def foo():
x=4
def bar():
print x # Accesses x from foo's scope
bar() # Prints 4
x=5
bar() # Prints 5
```
**Restrictions:**
Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new **local** variable instead of affecting the variable in the parent scope. For example:
```
global_var1 = []
global_var2 = 1
def func():
# This is OK: It's just accessing, not rebinding
global_var1.append(4)
# This won't affect global_var2. Instead it creates a new variable
global_var2 = 2
local1 = 4
def embedded_func():
# Again, this doen't affect func's local1 variable. It creates a
# new local variable also called local1 instead.
local1 = 5
print local1
embedded_func() # Prints 5
print local1 # Prints 4
```
In order to actually modify the bindings of global variables from within a function scope, you need to specify that the variable is global with the global keyword. Eg:
```
global_var = 4
def change_global():
global global_var
global_var = global_var + 1
```
Currently there is no way to do the same for variables in enclosing *function* scopes, but Python 3 introduces a new keyword, "`nonlocal`" which will act in a similar way to global, but for nested function scopes. |
Short Description of Scoping Rules | 291,978 | 228 | 2008-11-15T01:48:37Z | 23,471,004 | 44 | 2014-05-05T11:08:54Z | [
"python",
"scope",
"dynamic-languages"
] | What **exactly** are the Python scoping rules?
If I have some code:
```
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
```
Where is *x* found? Some possible choices include the list above:
1. In the enclosing source file
2. In the class namespace
3. In the function definition
4. In the for loop index variable
5. Inside the for loop
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers. | There was no thorough answer concerning Python3 time, so I made an answer here.
As provided in other answers, there are 4 basic scopes, the LEGB, for Local, Enclosing, Global and Builtin. In addition to those, there is a special scope, the **class body**, which does not comprise an enclosing scope for methods defined within the class; any assignments within the class body make the variable from there on be bound in the class body.
Especially, **no** block statement, besides `def` and `class`, create a variable scope. In Python 2 the list comprehension does not create a variable scope, however in Python 3 the loop variable is created in a new scope.
To demonstrate the peculiarities of the class body
```
x = 0
class X(object):
y = x
x = x + 1 # x is now a variable
z = x
def method(self):
print(self.x) # -> 1
print(x) # -> 0, the global x
print(y) # -> NameError: global name 'y' is not defined
inst = X()
print(inst.x, inst.y, inst.z, x) # -> (1, 0, 1, 0)
```
Thus unlike in function body, you can reassign the variable to the same name in class body, to get a class variable with the same name; further lookups on this name resolve
to the class variable instead.
---
One of the greater surprises to many newcomers to Python is that a `for` loop does not create a variable scope. In Python 2 the list comprehensions do not create a scope either (while generators and dict comprehensions do!) Instead they leak the value in the function or the global scope:
```
>>> [ i for i in range(5) ]
>>> i
4
```
The comprehensions can be used as a cunning (or awful if you will) way to make modifiable variables within lambda expressions in Python 2 - a lambda expression does create a variable scope, like the `def` statement would, but within lambda no statements are allowed. Assignment being a statement in Python means that no variable assignments in lambda are allowed, but a list comprehension is an expression...
This behaviour has been fixed in Python 3 - no comprehension expressions or generators leak variables.
---
The global really means the module scope; the main python module is the `__main__`; all imported modules are accessible through the `sys.modules` variable; to get access to `__main__` one can use `sys.modules['__main__']`, or `import __main__`; it is perfectly acceptable to access and assign attributes there; they will show up as variables in the global scope of the main module.
---
If a name is ever assigned to in the current scope (except in the class scope), it will be considered belonging to that scope, otherwise it will be considered to belonging to any enclosing scope that assigns to the variable (it might not be assigned yet, or not at all), or finally the global scope. If the variable is considered local, but it is not set yet, or has been deleted, reading the variable value will result in `UnboundLocalError`, which is a subclass of `NameError`.
```
x = 5
def foobar()
print(x) # UnboundLocalError!
x += 1 # assignment here makes x a local variable!
```
The scope can declare that it explicitly wants to modify the global (module scope) variable, with the global keyword:
```
x = 5
def foobar():
global x
print(x) # -> 5
x += 1
foobar()
print(x) # -> 6
```
This also is possible even if it was shadowed in enclosing scope:
```
x = 5
y = 13
def make_closure():
x = 42
y = 911
def func():
global x # sees the global value
print(x, y)
x += 1
return func
func = make_closure()
func() # -> print 5 911
print(x, y) # -> 6 13
```
In python 2 there is no easy way to modify the value in the enclosing scope; usually this is simulated by having a mutable value, such as a list with length of 1:
```
def make_closure():
value = [0]
def get_next_value():
value[0] += 1
return value[0]
return get_next_value
get_next = make_closure()
print(get_next()) # -> 1
print(get_next()) # -> 2
```
However in python 3, the `nonlocal` comes to rescue:
```
def make_closure():
value = 0
def get_next_value():
nonlocal value
value += 1
return value
return get_next_value
get_next = make_closure() # identical behavior to the previous example.
```
---
Any variable that is not deemed to be local to the current scope, or any enclosing scope, is a global variable. A global name is looked up in the module global dictionary; if not found, the global is then looked up from the builtins module; the name of the module was changed from python 2 to python 3; in python 2 it was `__builtin__` and in python 3 it is now called `builtins`. If you assign to an attribute of builtins module, it will be visible thereafter to any module as a readable global variable, unless that module shadows them with its own global variable with the same name.
---
Reading the builtin module can also be useful; suppose that you want the python 3 style print function in some parts of file, but other parts of file still use the `print` statement, if your python version is >= 2.6, you can get the new style function as:
```
import __builtin__
print3 = __builtin__.__dict__['print']
```
The `from __future__ import print_function` actually does not import the `print` function anywhere in Python 2 - instead it just disables the parsing rules for `print` statement in the current module, handling `print` like any other variable identifier, and thus allowing the `print` the function be looked up in the builtins. |
Short Description of Scoping Rules | 291,978 | 228 | 2008-11-15T01:48:37Z | 34,094,235 | 9 | 2015-12-04T17:38:37Z | [
"python",
"scope",
"dynamic-languages"
] | What **exactly** are the Python scoping rules?
If I have some code:
```
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
```
Where is *x* found? Some possible choices include the list above:
1. In the enclosing source file
2. In the class namespace
3. In the function definition
4. In the for loop index variable
5. Inside the for loop
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers. | A slightly more complete example of scope:
```
x = 100
print "1. Global x:", x
class Test(object):
y = x
print "2. Enclosed y:", y
x = x + 1
print "3. Enclosed x:", x
z = x
def method(self):
print "4. Enclosed self.x", self.x
print "5. Global x", x
try:
print y
except NameError, e:
print "6.", e
def method_local_ref(self):
try:
print x
except UnboundLocalError, e:
print "7.", e
x = 200
print "8. Local x", x
inst = Test()
inst.method()
inst.method_local_ref()
```
output:
> 1. Global x: 100
> 2. Enclosed y: 100
> 3. Enclosed x: 101
> 4. Enclosed self.x 101
> 5. Global x 100
> 6. global name 'y' is not defined
> 7. local variable 'x' referenced before assignment
> 8. Local x 200 |
Polling the keyboard (detect a keypress) in python | 292,095 | 43 | 2008-11-15T03:29:09Z | 292,770 | 19 | 2008-11-15T17:09:00Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
] | How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):
```
while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
```
What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required. | The standard approach is to use the [select](https://docs.python.org/2/library/select.html) module.
However, this doesn't work on Windows. For that, you can use the [msvcrt](https://docs.python.org/2/library/msvcrt.html#console-i-o) module's keyboard polling.
Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device. |
Polling the keyboard (detect a keypress) in python | 292,095 | 43 | 2008-11-15T03:29:09Z | 303,976 | 10 | 2008-11-20T00:32:05Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
] | How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):
```
while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
```
What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required. | Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:
```
import msvcrt
def kbfunc():
x = msvcrt.kbhit()
if x:
ret = ord(msvcrt.getch())
else:
ret = 0
return ret
``` |
Polling the keyboard (detect a keypress) in python | 292,095 | 43 | 2008-11-15T03:29:09Z | 1,450,063 | 12 | 2009-09-20T01:47:23Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
] | How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):
```
while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
```
What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required. | ```
import sys
import select
def heardEnter():
i,o,e = select.select([sys.stdin],[],[],0.0001)
for s in i:
if s == sys.stdin:
input = sys.stdin.readline()
return True
return False
``` |
Polling the keyboard (detect a keypress) in python | 292,095 | 43 | 2008-11-15T03:29:09Z | 3,524,350 | 7 | 2010-08-19T17:12:50Z | [
"python",
"console",
"keyboard",
"blocking",
"nonblocking"
] | How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):
```
while 1:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
```
What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required. | A solution using the curses module. Printing a numeric value corresponding to each key pressed:
```
import curses
def main(stdscr):
# do not wait for input when calling getch
stdscr.nodelay(1)
while True:
# get keyboard input, returns -1 if none available
c = stdscr.getch()
if c != -1:
# print numeric value
stdscr.addstr(str(c) + ' ')
stdscr.refresh()
# return curser to start position
stdscr.move(0, 0)
if __name__ == '__main__':
curses.wrapper(main)
``` |
wxPython, Set value of StaticText() | 293,344 | 24 | 2008-11-16T01:52:15Z | 293,350 | 18 | 2008-11-16T02:00:54Z | [
"python",
"wxpython"
] | I am making a little GUI frontend for a app at the moment using wxPython.
I am using `wx.StaticText()` to create a place to hold some text, code below:
```
content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE)
```
I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the `StaticText()` to the MySQL data or what else could I use the hold the data.
I have tried using the below method:
```
contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL)
content.SetValue("New Text")
```
This displays the data fine but after the data is loaded you can edit the data and I do not want this.
Hope you guys understand what I am trying to do, I am new to Python :)
Cheers | `wx.TextCtrl` has a style called `wx.TE_READONLY` . Use that to make it read-only.
As a sidenode, you can use the [C++ wxWidgets Manual](http://docs.wxwidgets.org/stable/wx_contents.html) for wxPython aswell. Where special handling for wxPython or other ports is required, the manual often points out the difference. |
wxPython, Set value of StaticText() | 293,344 | 24 | 2008-11-16T01:52:15Z | 294,100 | 50 | 2008-11-16T16:55:03Z | [
"python",
"wxpython"
] | I am making a little GUI frontend for a app at the moment using wxPython.
I am using `wx.StaticText()` to create a place to hold some text, code below:
```
content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE)
```
I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the `StaticText()` to the MySQL data or what else could I use the hold the data.
I have tried using the below method:
```
contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL)
content.SetValue("New Text")
```
This displays the data fine but after the data is loaded you can edit the data and I do not want this.
Hope you guys understand what I am trying to do, I am new to Python :)
Cheers | If you are using a [wx.StaticText()](http://docs.wxwidgets.org/stable/wx_wxstatictext.html#wxstatictextsetlabel) you can just:
```
def __init__(self, parent, *args, **kwargs): #frame constructor, etc.
self.some_text = wx.StaticText(panel, wx.ID_ANY, label="Awaiting MySQL Data", style=wx.ALIGN_CENTER)
def someFunction(self):
mysql_data = databasemodel.returnData() #query your database to return a string
self.some_text.SetLabel(mysql_data)
```
As litb mentioned, the wxWidgets docs are often much easier to use than the [wxPython docs](http://wxpython.org/docs/api/wx.StaticText-class.html). In order to see that the SetLabel() function can be applied to a wx.StaticText instance, you have to travel up the namespace hierarchy in the wxPython docs to the [wxWindow superclass](http://wxpython.org/docs/api/wx.Window-class.html#SetLabel), from which wx.StaticText is subclassed. There are a few things different in wxPython from wxWidgets, and it can be challenging to find out what they are. Fortunately, a lot of the time, the differences are convenience functions that have been added to wxPython and are not found in wxWidgets. |
Python object deleting itself | 293,431 | 45 | 2008-11-16T03:29:59Z | 293,447 | 60 | 2008-11-16T03:41:12Z | [
"python",
"memory-management",
"instance"
] | Why won't this work? I'm trying to make an instance of a class delete itself.
```
>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
``` | 'self' is only a reference to the object. 'del self' is deleting the 'self' reference from the local namespace of the kill function, instead of the actual object.
To see this for yourself, look at what happens when these two functions are executed:
```
>>> class A():
... def kill_a(self):
... print self
... del self
... def kill_b(self):
... del self
... print self
...
>>> a = A()
>>> b = A()
>>> a.kill_a()
<__main__.A instance at 0xb771250c>
>>> b.kill_b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in kill_b
UnboundLocalError: local variable 'self' referenced before assignment
``` |
Python object deleting itself | 293,431 | 45 | 2008-11-16T03:29:59Z | 293,454 | 36 | 2008-11-16T03:46:09Z | [
"python",
"memory-management",
"instance"
] | Why won't this work? I'm trying to make an instance of a class delete itself.
```
>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
``` | You don't need to use del to delete instances in the first place. Once the last reference to an object is gone, the object will be garbage collected. Maybe you should tell us more about the full problem. |
Python object deleting itself | 293,431 | 45 | 2008-11-16T03:29:59Z | 293,920 | 12 | 2008-11-16T14:26:51Z | [
"python",
"memory-management",
"instance"
] | Why won't this work? I'm trying to make an instance of a class delete itself.
```
>>> class A():
def kill(self):
del self
>>> a = A()
>>> a.kill()
>>> a
<__main__.A instance at 0x01F23170>
``` | In this specific context, your example doesn't make a lot of sense.
When a Being picks up an Item, the item retains an individual existence. It doesn't disappear because it's been picked up. It still exists, but it's (a) in the same location as the Being, and (b) no longer eligible to be picked up. While it's had a state change, it still exists.
There is a two-way association between Being and Item. The Being has the Item in a collection. The Item is associated with a Being.
When an Item is picked up by a Being, two things have to happen.
* The Being how adds the Item in some `set` of items. Your `bag` attribute, for example, could be such a `set`. [A `list` is a poor choice -- does order matter in the bag?]
* The Item's location changes from where it used to be to the Being's location. There are probably two classes os Items - those with an independent sense of location (because they move around by themselves) and items that have to delegate location to the Being or Place where they're sitting.
Under no circumstances does any Python object ever need to get deleted. If an item is "destroyed", then it's not in a Being's bag. It's not in a location.
```
player.bag.remove(cat)
```
Is all that's required to let the cat out of the bag. Since the cat is not used anywhere else, it will both exist as "used" memory and not exist because nothing in your program can access it. It will quietly vanish from memory when some quantum event occurs and memory references are garbage collected.
On the other hand,
```
here.add( cat )
player.bag.remove(cat)
```
Will put the cat in the current location. The cat continues to exist, and will not be put out with the garbage. |
How do I fix wrongly nested / unclosed HTML tags? | 293,482 | 15 | 2008-11-16T04:14:57Z | 293,484 | 9 | 2008-11-16T04:17:52Z | [
"python",
"html",
"algorithm",
"xhtml"
] | I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.
For example, something like
```
<p>
<ul>
<li>Foo
```
becomes
```
<p>
<ul>
<li>Foo</li>
</ul>
</p>
```
Any help would be appreciated :) | Run it through [Tidy](http://tidy.sourceforge.net/) or one of its ported [libraries](http://utidylib.berlios.de/).
Try to code it by hand and you *will* want to gouge your eyes out. |
How do I fix wrongly nested / unclosed HTML tags? | 293,482 | 15 | 2008-11-16T04:14:57Z | 293,558 | 24 | 2008-11-16T06:05:25Z | [
"python",
"html",
"algorithm",
"xhtml"
] | I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.
For example, something like
```
<p>
<ul>
<li>Foo
```
becomes
```
<p>
<ul>
<li>Foo</li>
</ul>
</p>
```
Any help would be appreciated :) | using BeautifulSoup:
```
from BeautifulSoup import BeautifulSoup
html = "<p><ul><li>Foo"
soup = BeautifulSoup(html)
print soup.prettify()
```
gets you
```
<p>
<ul>
<li>
Foo
</li>
</ul>
</p>
```
As far as I know, you can't control putting the <li></li> tags on separate lines from Foo.
using Tidy:
```
import tidy
html = "<p><ul><li>Foo"
print tidy.parseString(html, show_body_only=True)
```
gets you
```
<ul>
<li>Foo</li>
</ul>
```
Unfortunately, I know of no way to keep the <p> tag in the example. Tidy interprets it as an empty paragraph rather than an unclosed one, so doing
```
print tidy.parseString(html, show_body_only=True, drop_empty_paras=False)
```
comes out as
```
<p></p>
<ul>
<li>Foo</li>
</ul>
```
Ultimately, of course, the <p> tag in your example is redundant, so you might be fine with losing it.
Finally, Tidy can also do indenting:
```
print tidy.parseString(html, show_body_only=True, indent=True)
```
becomes
```
<ul>
<li>Foo
</li>
</ul>
```
All of these have their ups and downs, but hopefully one of them is close enough. |
Python for Autohotkey style key-combination sniffing, automation? | 294,285 | 10 | 2008-11-16T19:43:27Z | 294,461 | 7 | 2008-11-16T22:05:51Z | [
"python",
"autohotkey"
] | I want to automate several tasks (eg. simulate eclipse style ctrl-shift-r open dialog for other editors). The general pattern is: the user will press some key combination, my program will detect it and potentially pop up a dialog to get user input, and then run a corresponding command, typically by running an executable.
My target environment is windows, although cross-platform would be nice. My program would be started once, read a configuration file, and sit in the background till triggered by a key combination or other event.
Basically autohotkey.
Why not just use autohotkey? I actually have quite a few autohotkey macros, but I'd prefer to use a saner language.
My question is: is there a good way to have a background python process detect key combinations?
Update: found the answer using pyHook and the win32 extensions:
```
import pyHook
import pythoncom
def OnKeyboardEvent(event):
print event.Ascii
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
while True:
pythoncom.PumpMessages()
``` | You may want to look at [AutoIt](http://www.autoitscript.com/autoit3/). It does everything that AutoHotKey can do, but the language syntax doesn't make you want to pull your hair out. Additonally, it has COM bindings so you can use most of it's abilities easily in python if you so desired. I've posted about how to do it here [before](http://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python#155587). |
unpacking an array of arguments in php | 294,313 | 20 | 2008-11-16T20:05:42Z | 294,325 | 20 | 2008-11-16T20:08:30Z | [
"php",
"python",
"arguments",
"iterable-unpacking"
] | Python provides the "\*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:
```
args = [3, 6]
range(*args) # call with arguments unpacked from a list
```
This is equivalent to:
```
range(3, 6)
```
Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP? | You can use [`call_user_func_array()`](http://www.php.net/call_user_func_array) to achieve that:
`call_user_func_array("range", $args);` to use your example. |
unpacking an array of arguments in php | 294,313 | 20 | 2008-11-16T20:05:42Z | 23,164,267 | 8 | 2014-04-19T00:14:26Z | [
"php",
"python",
"arguments",
"iterable-unpacking"
] | Python provides the "\*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:
```
args = [3, 6]
range(*args) # call with arguments unpacked from a list
```
This is equivalent to:
```
range(3, 6)
```
Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP? | In `php5.6` the [`...` operator](http://docs.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat) has been added. Using it, you can get rid of `call_user_func_array()` for this simpler alternative. For example having a function
```
function add($a, $b){
return $a + $b;
}
```
and your array `$list = [4, 6];` (after php5.5 you can declare arrays in this way).
You can call your function with `...`:
`echo add(...$list);` |
How do I find userid by login (Python under *NIX) | 294,470 | 11 | 2008-11-16T22:11:25Z | 294,480 | 20 | 2008-11-16T22:19:52Z | [
"python",
"linux",
"unix",
"process-management"
] | I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find `uid` if I have `login`?
I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody? | You might want to have a look at the [pwd](http://docs.python.org/library/pwd.html) module in the python stdlib, for example:
```
import pwd
pw = pwd.getpwnam("nobody")
uid = pw.pw_uid
```
it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually |
Python UPnP/IGD Client Implementation? | 294,504 | 11 | 2008-11-16T22:38:41Z | 298,052 | 7 | 2008-11-18T07:26:00Z | [
"python",
"networking",
"nat",
"upnp"
] | I am searching for an open-source implementation of an [UPnP](http://elinux.org/UPnP) client in Python, and more specifically of its [Internet Gateway Device](http://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol) (IGD) part.
For now, I have only been able to find UPnP Media Server implementations, in projects such as [PyMediaServer](http://pymediaserver.sourceforge.net/), [PyMedS](http://resnet.uoregon.edu/~gurney_j/jmpc/pymeds.html), [BRisa](http://brisa.garage.maemo.org/) or [Coherence](https://coherence.beebits.net/).
I am sure I could use those code bases as a start, but the Media Server part will introduce unneeded complexity.
So can you recommend a client UPnP (and hopefully IGD) Python library? An alternative would be to dispatch calls to a C library such as [MiniUPnP](http://miniupnp.free.fr/), but I would much prefer a pure Python implementation.
Update: an interesting, kind of related discussion of SSDP and UPnP is available on [StackOverflow](http://stackoverflow.com/questions/22321/remoting-server-auto-discovery-broadcast-or-not). | MiniUPnP source code contains a Python sample code using the C library as an extension module (see `testupnpigd.py`), which I consider as a proper solution to my problem.
Rationale: this is not the pure Python solution I was looking for, but:
* significant effort has already been invested in this library,
* it is lightweight (it does not address Media Server issues),
* IGD is typically only used at connection setup, so not integrating it tighter with the Python code does not seem like an issue,
* as a bonus, it also provides a NAT-PNP implementation (the Apple concurrent of IGD, part of [Bonjour](http://developer.apple.com/networking/bonjour/specs.html)). |
What are some techniques for code generation? | 294,520 | 4 | 2008-11-16T22:58:22Z | 294,528 | 8 | 2008-11-16T23:06:18Z | [
"c++",
"python",
"code-generation"
] | I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp> . | I wrote [Cog](http://nedbatchelder.com/code/cog/index.html) partly to generate C++ code from an XML data schema. It lets you use Python code embedded in C++ source files to generate C++ source. |
What are some techniques for code generation? | 294,520 | 4 | 2008-11-16T22:58:22Z | 294,542 | 7 | 2008-11-16T23:12:17Z | [
"c++",
"python",
"code-generation"
] | I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp> . | One technique I've used for code generation is to not worry at all about formatting in the code generator. Then, as a next step after generating the code, run it through [`indent`](http://www.gnu.org/software/indent/) to format it reasonably so you can read (and more importantly, debug) it. |
Flattening one-to-many relationship in Django | 294,712 | 7 | 2008-11-17T01:47:51Z | 294,723 | 10 | 2008-11-17T02:00:37Z | [
"python",
"django",
"list",
"flatten"
] | I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients:
```
class Book(models.Model):
name = models.CharField(max_length=64)
class Recipe(models.Model):
book = models.ForeignKey(Book)
name = models.CharField(max_length=64)
class Ingredient(models.Model):
text = models.CharField(max_length=128)
recipe = models.ForeignKey(Recipe)
```
I'd like a flat list of all ingredients in all recipes from a particular book. What's the best way to express this in Python?
If I was using LINQ, I might write something like this:
```
var allIngredients = from recipe in book.Recipes
from ingredient in recipe.Ingredients
select ingredient;
``` | Actually, it looks like there's a better approach using filter:
```
my_book = Book.objects.get(pk=1)
all_ingredients = Ingredient.objects.filter(recipe__book=my_book)
``` |
Convert a string to preexisting variable names | 295,058 | 20 | 2008-11-17T07:32:09Z | 295,064 | 23 | 2008-11-17T07:37:00Z | [
"python"
] | How do I convert a string to the variable name in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
For example, if the program contains a object named `self.post` that contains a variable named, I want to do something like:
```
somefunction("self.post.id") = |Value of self.post.id|
``` | As referenced in Stack Overflow question *[Inplace substitution from ConfigParser](http://stackoverflow.com/questions/295028/)*, you're looking for `eval()`:
```
print eval('self.post.id') # Prints the value of self.post.id
``` |
Convert a string to preexisting variable names | 295,058 | 20 | 2008-11-17T07:32:09Z | 295,113 | 10 | 2008-11-17T08:47:58Z | [
"python"
] | How do I convert a string to the variable name in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
For example, if the program contains a object named `self.post` that contains a variable named, I want to do something like:
```
somefunction("self.post.id") = |Value of self.post.id|
``` | Also, there is the **[globals()](https://docs.python.org/2/library/functions.html#globals)** function in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) which returns a dictionary with all the defined variables. You could also use something like this:
```
print globals()["myvar"]
``` |
Convert a string to preexisting variable names | 295,058 | 20 | 2008-11-17T07:32:09Z | 296,060 | 42 | 2008-11-17T16:26:46Z | [
"python"
] | How do I convert a string to the variable name in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
For example, if the program contains a object named `self.post` that contains a variable named, I want to do something like:
```
somefunction("self.post.id") = |Value of self.post.id|
``` | Note: do **not** use eval in any case where you are getting the name to look up from user entered input. For example, if this comes from a web page, there is nothing preventing anyone from entering:
```
__import__("os").system("Some nasty command like rm -rf /*")
```
as the argument. Better is to limit to well-defined lookup locations such as a dictionary or instance using [getattr()](https://docs.python.org/2/library/functions.html#getattr). For example, to find the "post" value on self, use:
```
varname = "post"
value = getattr(self, varname) # Gets self.post
```
Similarly to set it, use setattr():
```
value = setattr(self, varname, new_value)
```
To handle [fully qualified names](https://en.wikipedia.org/wiki/Fully_qualified_name), like "post.id", you could use something like the below functions in place of getattr() / [setattr()](https://docs.python.org/2/library/functions.html#setattr).
```
def getattr_qualified(obj, name):
for attr in name.split("."):
obj = getattr(obj, attr)
return obj
def setattr_qualified(obj, name, value):
parts = name.split(".")
for attr in parts[:-1]:
obj = getattr(obj, attr)
setattr(obj, parts[-1], value)
``` |
Convert a string to preexisting variable names | 295,058 | 20 | 2008-11-17T07:32:09Z | 1,732,924 | 13 | 2009-11-14T01:32:15Z | [
"python"
] | How do I convert a string to the variable name in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
For example, if the program contains a object named `self.post` that contains a variable named, I want to do something like:
```
somefunction("self.post.id") = |Value of self.post.id|
``` | You could do something like what Geo recommended, or go with:
```
>>> wine = 'pinot_noir'
>>> vars()[wine] = 'yum'
>>> pinot_noir
'yum'
```
Note: vars() and globals() are the same, I'm just used to using vars()
I'm surprised nobody called me out on this! Anyway, it's `vars()` and *`locals()`* that are the same. |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 295,146 | 77 | 2008-11-17T09:10:49Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | This whitelist approach (ie, allowing only the chars present in valid\_chars) will work if there aren't limits on the formatting of the files or combination of valid chars that are illegal (like ".."), for example, what you say would allow a filename named " . txt" which I think is not valid on Windows. As this is the most simple approach I'd try to remove whitespace from the valid\_chars and prepend a known valid string in case of error, any other approach will have to know about what is allowed where to cope with [Windows file naming limitations](http://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-file-name-under-windows) and thus be a lot more complex.
```
>>> import string
>>> valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
>>> valid_chars
'-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
>>> filename = "This Is a (valid) - filename%$&$ .txt"
>>> ''.join(c for c in filename if c in valid_chars)
'This Is a (valid) - filename .txt'
``` |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 295,150 | 70 | 2008-11-17T09:12:02Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | What is the reason to use the strings as file names? If human readability is not a factor I would go with base64 module which can produce file system safe strings. It won't be readable but you won't have to deal with collisions and it is reversible.
```
import base64
file_name_string = base64.urlsafe_b64encode(your_string)
```
**Update**: Changed based on Matthew comment. |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 295,152 | 61 | 2008-11-17T09:12:49Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | You can use list comprehension together with the string methods.
```
>>> s
'foo-bar#baz?qux@127/\\9]'
>>> "".join(x for x in s if x.isalnum())
'foobarbazqux1279'
``` |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 295,206 | 27 | 2008-11-17T09:57:40Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | Just to further complicate things, you are not guaranteed to get a valid filename just by removing invalid characters. Since allowed characters differ on different filenames, a conservative approach could end up turning a valid name into an invalid one. You may want to add special handling for the cases where:
* The string is all invalid characters (leaving you with an empty string)
* You end up with a string with a special meaning, eg "." or ".."
* On windows, [certain device names](http://msdn.microsoft.com/en-us/library/aa365247.aspx) are reserved. For instance, you can't create a file named "nul", "nul.txt" (or nul.anything in fact) The reserved names are:
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9
You can probably work around these issues by prepending some string to the filenames that can never result in one of these cases, and stripping invalid characters. |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 295,298 | 12 | 2008-11-17T10:45:54Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | Keep in mind, there are actually no restrictions on filenames on Unix systems other than
* It may not contain \0
* It may not contain /
Everything else is fair game.
```
$ touch "
> even multiline
> haha
> ^[[31m red ^[[0m
> evil"
$ ls -la
-rw-r--r-- 0 Nov 17 23:39 ?even multiline?haha??[31m red ?[0m?evil
$ ls -lab
-rw-r--r-- 0 Nov 17 23:39 \neven\ multiline\nhaha\n\033[31m\ red\ \033[0m\nevil
$ perl -e 'for my $i ( glob(q{./*even*}) ){ print $i; } '
./
even multiline
haha
red
evil
```
Yes, i just stored ANSI Colour Codes in a file name and had them take effect.
For entertainment, put a BEL character in a directory name and watch the fun that ensues when you CD into it ;) |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 295,466 | 84 | 2008-11-17T12:23:52Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | You can look at the [Django framework](http://www.djangoproject.com) for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly.
Their `template/defaultfilters.py` (at around line 183) defines a function, `slugify`, that's probably the gold standard for this kind of thing. Essentially, their code is the following.
```
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
value = unicode(re.sub('[-\s]+', '-', value))
```
There's more, but I left it out, since it doesn't address slugification, but escaping. |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 698,714 | 12 | 2009-03-30T19:40:17Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | This is the solution I ultimately used:
```
import unicodedata
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
def removeDisallowedFilenameChars(filename):
cleanedFilename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore')
return ''.join(c for c in cleanedFilename if c in validFilenameChars)
```
The unicodedata.normalize call replaces accented characters with the unaccented equivalent, which is better than simply stripping them out. After that all disallowed characters are removed.
My solution doesn't prepend a known string to avoid possible disallowed filenames, because I know they can't occur given my particular filename format. A more general solution would need to do so. |
Turn a string into a valid filename in Python | 295,135 | 160 | 2008-11-17T09:02:07Z | 29,942,164 | 7 | 2015-04-29T11:19:47Z | [
"python",
"filenames",
"slug",
"sanitize"
] | I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like `"_-.() "`. What's the most elegant solution?
The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines. | There is a nice project on Github called [python-slugify](https://github.com/un33k/python-slugify):
Install:
```
pip install python-slugify
```
Then use:
```
>>> from slugify import slugify
>>> txt = "This\ is/ a%#$ test ---"
>>> slugify(txt)
'this-is-a-test'
``` |
How do I add a directory with a colon to PYTHONPATH? | 295,195 | 3 | 2008-11-17T09:46:19Z | 295,276 | 7 | 2008-11-17T10:38:26Z | [
"python",
"bash",
"shell"
] | The problem is simple:
Using bash, I want to add a directory to my PYTHONPATH for ease of script execution. Unfortunately, the directory I want to use has a : in it. So I try each of the following
```
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com:3344/
export PYTHONPATH=${PYTHONPATH}:/home/shane/mywebsite.com\:3344/
export PYTHONPATH=${PYTHONPATH}:"/home/shane/mywebsite.com:3344/"
```
None of these work. Every time, the path is created as two separate directories on the path in python.
My question is, is it possible to do this for bash?
If so, what's the syntax required? | The problem is not with bash. It should be setting your environment variable correctly, complete with the `:` character.
The problem, instead, is with Python's parsing of the `PYTHONPATH` variable. Following the example set by the [`PATH` variable](http://sourceware.org/cgi-bin/cvsweb.cgi/libc/posix/execvp.c?rev=1.27&content-type=text/x-cvsweb-markup&cvsroot=glibc), it seems there is no escape character at all, so there is no way to make it interpret the `:` as something other than a separator. You can see it for yourself in the [Python interpreter source code](http://svn.python.org/view/python/trunk/Modules/getpath.c?rev=54257&view=auto).
The only solution is, as several people already mentioned, to use a symlink or something else to allow you to give a colon-less name for your directories. |
How can one mock/stub python module like urllib | 295,438 | 57 | 2008-11-17T12:07:40Z | 295,465 | 8 | 2008-11-17T12:23:30Z | [
"python",
"unit-testing",
"testing",
"mocking"
] | I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.
What is the best way to control what urllib.urlopen returns? | Probably the best way to handle this is to split up the code, so that logic that processes the page contents is split from the code that fetches the page.
Then pass an instance of the fetcher code into the processing logic, then you can easily replace it with a mock fetcher for the unit test.
e.g.
```
class Processor(oject):
def __init__(self, fetcher):
self.m_fetcher = fetcher
def doProcessing(self):
## use self.m_fetcher to get page contents
class RealFetcher(object):
def fetchPage(self, url):
## get real contents
class FakeFetcher(object):
def fetchPage(self, url):
## Return whatever fake contents are required for this test
``` |
How can one mock/stub python module like urllib | 295,438 | 57 | 2008-11-17T12:07:40Z | 295,481 | 78 | 2008-11-17T12:32:42Z | [
"python",
"unit-testing",
"testing",
"mocking"
] | I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.
What is the best way to control what urllib.urlopen returns? | Another simple approach is to have your test override urllib's `urlopen()` function. For example, if your module has
```
import urllib
def some_function_that_uses_urllib():
...
urllib.urlopen()
...
```
You could define your test like this:
```
import mymodule
def dummy_urlopen(url):
...
mymodule.urllib.urlopen = dummy_urlopen
```
Then, when your tests invoke functions in `mymodule`, `dummy_urlopen()` will be called instead of the real `urlopen()`. Dynamic languages like Python make it super easy to stub out methods and classes for testing.
See my blog posts at <http://softwarecorner.wordpress.com/> for more information about stubbing out dependencies for tests. |
How can one mock/stub python module like urllib | 295,438 | 57 | 2008-11-17T12:07:40Z | 295,503 | 26 | 2008-11-17T12:49:46Z | [
"python",
"unit-testing",
"testing",
"mocking"
] | I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.
What is the best way to control what urllib.urlopen returns? | Did you give [Mox](https://pypi.python.org/pypi/mox) a look? It should do everything you need. Here is a simple interactive session illustrating the solution you need:
```
>>> import urllib
>>> # check that it works
>>> urllib.urlopen('http://www.google.com/')
<addinfourl at 3082723820L ...>
>>> # check what happens when it doesn't
>>> urllib.urlopen('http://hopefully.doesnotexist.com/')
#-- snip --
IOError: [Errno socket error] (-2, 'Name or service not known')
>>> # OK, let's mock it up
>>> import mox
>>> m = mox.Mox()
>>> m.StubOutWithMock(urllib, 'urlopen')
>>> # We can be verbose if we want to :)
>>> urllib.urlopen(mox.IgnoreArg()).AndRaise(
... IOError('socket error', (-2, 'Name or service not known')))
>>> # Let's check if it works
>>> m.ReplayAll()
>>> urllib.urlopen('http://www.google.com/')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/site-packages/mox.py", line 568, in __call__
raise expected_method._exception
IOError: [Errno socket error] (-2, 'Name or service not known')
>>> # yay! now unset everything
>>> m.UnsetStubs()
>>> m.VerifyAll()
>>> # and check that it still works
>>> urllib.urlopen('http://www.google.com/')
<addinfourl at 3076773548L ...>
``` |
How can one mock/stub python module like urllib | 295,438 | 57 | 2008-11-17T12:07:40Z | 2,392,989 | 58 | 2010-03-06T15:31:31Z | [
"python",
"unit-testing",
"testing",
"mocking"
] | I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.
What is the best way to control what urllib.urlopen returns? | I am using [Mock's](http://www.voidspace.org.uk/python/mock/) patch decorator:
```
from mock import patch
[...]
@patch('urllib.urlopen')
def test_foo(self, urlopen_mock):
urlopen_mock.return_value = MyUrlOpenMock()
``` |
How can one mock/stub python module like urllib | 295,438 | 57 | 2008-11-17T12:07:40Z | 13,296,807 | 13 | 2012-11-08T20:01:37Z | [
"python",
"unit-testing",
"testing",
"mocking"
] | I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.
What is the best way to control what urllib.urlopen returns? | [HTTPretty](https://github.com/gabrielfalcao/HTTPretty) works in the exact same way that FakeWeb does. HTTPretty works in the socket layer, so it should work intercepting any python http client libraries. It's battle tested against urllib2, httplib2 and requests
```
import urllib2
from httpretty import HTTPretty, httprettified
@httprettified
def test_one():
HTTPretty.register_uri(HTTPretty.GET, "http://yipit.com/",
body="Find the best daily deals")
fd = urllib2.urlopen('http://yipit.com')
got = fd.read()
fd.close()
assert got == "Find the best daily deals"
``` |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | 27 | 2008-11-17T12:17:49Z | 295,564 | 27 | 2008-11-17T13:32:13Z | [
"python",
"pipe",
"subprocess"
] | How do I execute the following shell command using the Python [`subprocess`](https://docs.python.org/library/subprocess.html) module?
```
echo "input data" | awk -f script.awk | sort > outfile.txt
```
The input data will come from a string, so I don't actually need `echo`. I've got this far, can anyone explain how I get it to pipe through `sort` too?
```
p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
```
**UPDATE**: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place! | You'd be a little happier with the following.
```
import subprocess
awk_sort = subprocess.Popen( "awk -f script.awk | sort > outfile.txt",
stdin=subprocess.PIPE, shell=True )
awk_sort.communicate( b"input data\n" )
```
Delegate part of the work to the shell. Let it connect two processes with a pipeline.
You'd be a lot happier rewriting 'script.awk' into Python, eliminating awk and the pipeline.
**Edit**. Some of the reasons for suggesting that awk isn't helping.
[There are too many reasons to respond via comments.]
1. Awk is adding a step of no significant value. There's nothing unique about awk's processing that Python doesn't handle.
2. The pipelining from awk to sort, for large sets of data, may improve elapsed processing time. For short sets of data, it has no significant benefit. A quick measurement of `awk >file ; sort file` and `awk | sort` will reveal of concurrency helps. With sort, it rarely helps because sort is not a once-through filter.
3. The simplicity of "Python to sort" processing (instead of "Python to awk to sort") prevents the exact kind of questions being asked here.
4. Python -- while wordier than awk -- is also explicit where awk has certain implicit rules that are opaque to newbies, and confusing to non-specialists.
5. Awk (like the shell script itself) adds Yet Another Programming language. If all of this can be done in one language (Python), eliminating the shell and the awk programming eliminates two programming languages, allowing someone to focus on the value-producing parts of the task.
Bottom line: awk can't add significant value. In this case, awk is a net cost; it added enough complexity that it was necessary to ask this question. Removing awk will be a net gain.
**Sidebar** Why building a pipeline (`a | b`) is so hard.
When the shell is confronted with `a | b` it has to do the following.
1. Fork a child process of the original shell. This will eventually become b.
2. Build an os pipe. (not a Python subprocess.PIPE) but call `os.pipe()` which returns two new file descriptors that are connected via common buffer. At this point the process has stdin, stdout, stderr from its parent, plus a file that will be "a's stdout" and "b's stdin".
3. Fork a child. The child replaces its stdout with the new a's stdout. Exec the `a` process.
4. The b child closes replaces its stdin with the new b's stdin. Exec the `b` process.
5. The b child waits for a to complete.
6. The parent is waiting for b to complete.
I think that the above can be used recursively to spawn `a | b | c`, but you have to implicitly parenthesize long pipelines, treating them as if they're `a | (b | c)`.
Since Python has `os.pipe()`, `os.exec()` and `os.fork()`, and you can replace `sys.stdin` and `sys.stdout`, there's a way to do the above in pure Python. Indeed, you may be able to work out some shortcuts using `os.pipe()` and `subprocess.Popen`.
However, it's easier to delegate that operation to the shell. |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | 27 | 2008-11-17T12:17:49Z | 9,164,238 | 10 | 2012-02-06T17:20:01Z | [
"python",
"pipe",
"subprocess"
] | How do I execute the following shell command using the Python [`subprocess`](https://docs.python.org/library/subprocess.html) module?
```
echo "input data" | awk -f script.awk | sort > outfile.txt
```
The input data will come from a string, so I don't actually need `echo`. I've got this far, can anyone explain how I get it to pipe through `sort` too?
```
p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
```
**UPDATE**: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place! | ```
import subprocess
some_string = b'input_data'
sort_out = open('outfile.txt', 'wb', 0)
sort_in = subprocess.Popen('sort', stdin=subprocess.PIPE, stdout=sort_out).stdin
subprocess.Popen(['awk', '-f', 'script.awk'], stdout=sort_in,
stdin=subprocess.PIPE).communicate(some_string)
``` |
How do I use subprocess.Popen to connect multiple processes by pipes? | 295,459 | 27 | 2008-11-17T12:17:49Z | 16,709,666 | 8 | 2013-05-23T09:01:24Z | [
"python",
"pipe",
"subprocess"
] | How do I execute the following shell command using the Python [`subprocess`](https://docs.python.org/library/subprocess.html) module?
```
echo "input data" | awk -f script.awk | sort > outfile.txt
```
The input data will come from a string, so I don't actually need `echo`. I've got this far, can anyone explain how I get it to pipe through `sort` too?
```
p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
```
**UPDATE**: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place! | To emulate a shell pipeline:
```
from subprocess import check_call
check_call('echo "input data" | a | b > outfile.txt', shell=True)
```
without invoking the shell (see [17.1.4.2. Replacing shell pipeline](http://docs.python.org/2.7/library/subprocess.html#replacing-shell-pipeline)):
```
#!/usr/bin/env python
from subprocess import Popen, PIPE
a = Popen(["a"], stdin=PIPE, stdout=PIPE)
with a.stdin:
with a.stdout, open("outfile.txt", "wb") as outfile:
b = Popen(["b"], stdin=a.stdout, stdout=outfile)
a.stdin.write(b"input data")
statuses = [a.wait(), b.wait()] # both a.stdin/stdout are closed already
```
[`plumbum`](http://plumbum.readthedocs.org/en/latest/) provides some syntax sugar:
```
#!/usr/bin/env python
from plumbum.cmd import a, b # magic
(a << "input data" | b > "outfile.txt")()
```
The analog of:
```
#!/bin/sh
echo "input data" | awk -f script.awk | sort > outfile.txt
```
is:
```
#!/usr/bin/env python
from plumbum.cmd import awk, sort
(awk["-f", "script.awk"] << "input data" | sort > "outfile.txt")()
``` |
What is a partial class? | 295,670 | 8 | 2008-11-17T14:24:32Z | 295,676 | 19 | 2008-11-17T14:26:55Z | [
"c#",
"python",
"oop",
"programming-languages"
] | What is and how can it be used in C#.
Can you use the same concept in Python/Perl? | A [partial type](http://msdn.microsoft.com/en-us/library/wa80x488.aspx) (it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.
The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.
I've no idea whether Python/Perl have the same capabilities, I'm afraid. |
What is a partial class? | 295,670 | 8 | 2008-11-17T14:24:32Z | 295,760 | 9 | 2008-11-17T14:58:09Z | [
"c#",
"python",
"oop",
"programming-languages"
] | What is and how can it be used in C#.
Can you use the same concept in Python/Perl? | The c# partial class has been already explained here so I'll just cover the python part. You can use multiple inheritance to elegantly distribute the definition of a class.
```
class A_part1:
def m1(self):
print "m1"
class A_part2:
def m2(self):
print "m2"
class A(A_part1, A_part2):
pass
a = A()
a.m1()
a.m2()
``` |
Does python optimize modules when they are imported multiple times? | 296,036 | 22 | 2008-11-17T16:21:43Z | 296,062 | 34 | 2008-11-17T16:27:04Z | [
"python",
"python-import"
] | If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?
For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so
```
import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
```
or just
```
import MyLib
import ReallyBigLib
``` | Python modules could be considered as singletons... no matter how many times you import them they get initialized only once, so it's better to do:
```
import MyLib
import ReallyBigLib
```
Relevant documentation on the import statement:
<https://docs.python.org/2/reference/simple_stmts.html#the-import-statement>
> Once the name of the module is known (unless otherwise specified, the term âmoduleâ will refer to both packages and modules), searching for the module or package can begin. The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.
The imported modules are cached in [sys.modules](https://docs.python.org/2/library/sys.html#sys.modules):
> This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object. |
Does python optimize modules when they are imported multiple times? | 296,036 | 22 | 2008-11-17T16:21:43Z | 296,064 | 7 | 2008-11-17T16:27:44Z | [
"python",
"python-import"
] | If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?
For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so
```
import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
```
or just
```
import MyLib
import ReallyBigLib
``` | It makes no substantial difference. If the big module has already been loaded, the second import in your second example does nothing except adding 'ReallyBigLib' to the current namespace. |
Does python optimize modules when they are imported multiple times? | 296,036 | 22 | 2008-11-17T16:21:43Z | 298,106 | 12 | 2008-11-18T08:01:14Z | [
"python",
"python-import"
] | If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?
For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so
```
import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
```
or just
```
import MyLib
import ReallyBigLib
``` | As others have pointed out, Python maintains an internal list of all modules that have been imported. When you import a module for the first time, the module (a script) is executed in its own namespace until the end, the internal list is updated, and execution of continues after the import statement.
Try this code:
```
# module/file a.py
print "Hello from a.py!"
import b
# module/file b.py
print "Hello from b.py!"
import a
```
There is no loop: there is only a cache lookup.
```
>>> import b
Hello from b.py!
Hello from a.py!
>>> import a
>>>
```
One of the beauties of Python is how everything devolves to executing a script in a namespace. |
How do I copy files with specific file extension to a folder in my python (version 2.5) script? | 296,173 | 14 | 2008-11-17T17:02:43Z | 296,184 | 23 | 2008-11-17T17:06:37Z | [
"python",
"file",
"copy"
] | I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use `os.walk` but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance. | ```
import glob, os, shutil
files = glob.iglob(os.path.join(source_dir, "*.ext"))
for file in files:
if os.path.isfile(file):
shutil.copy2(file, dest_dir)
```
Read the [documentation](http://www.python.org/doc/2.5.2/lib/module-shutil.html) of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2() or shutil.copyfile()). |
How do I zip the contents of a folder using python (version 2.5)? | 296,499 | 27 | 2008-11-17T19:00:07Z | 296,722 | 29 | 2008-11-17T20:07:58Z | [
"python",
"file",
"zip",
"python-2.5"
] | Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance. | Adapted version of [the script](http://mail.python.org/pipermail/python-list/2006-May/384142.html) is:
```
#!/usr/bin/env python
from __future__ import with_statement
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import os
def zipdir(basedir, archivename):
assert os.path.isdir(basedir)
with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z:
for root, dirs, files in os.walk(basedir):
#NOTE: ignore empty directories
for fn in files:
absfn = os.path.join(root, fn)
zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path
z.write(absfn, zfn)
if __name__ == '__main__':
import sys
basedir = sys.argv[1]
archivename = sys.argv[2]
zipdir(basedir, archivename)
```
Example:
```
C:\zipdir> python -mzipdir c:\tmp\test test.zip
```
It creates `'C:\zipdir\test.zip'` archive with the contents of the `'c:\tmp\test'` directory. |
How do I zip the contents of a folder using python (version 2.5)? | 296,499 | 27 | 2008-11-17T19:00:07Z | 11,880,001 | 37 | 2012-08-09T09:04:52Z | [
"python",
"file",
"zip",
"python-2.5"
] | Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance. | On python 2.7 you might use: [shutil.make\_archive(base\_name, format[, root\_dir[, base\_dir[, verbose[, dry\_run[, owner[, group[, logger]]]]]]])](http://docs.python.org/library/shutil#shutil.make_archive).
**base\_name** archive name minus extension
**format** format of the archive
**root\_dir** directory to compress.
For example
```
shutil.make_archive(target_file, format="bztar", root_dir=compress_me)
``` |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | 61 | 2008-11-17T19:48:44Z | 296,663 | 7 | 2008-11-17T19:52:38Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] | We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:
Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?
Primarily languages will be Java, C/C++, Python, and PHP.
Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing [compressed JSON performing similar / better than Thrift / Protocol Buffers](http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/), so I'm throwing JSON into this question as well. | You may be interested in this question: ["Biggest differences of Thrift vs Protocol Buffers?"](http://stackoverflow.com/questions/69316/biggest-differences-of-thrift-vs-protocol-buffers) |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | 61 | 2008-11-17T19:48:44Z | 297,448 | 14 | 2008-11-18T00:13:01Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] | We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:
Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?
Primarily languages will be Java, C/C++, Python, and PHP.
Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing [compressed JSON performing similar / better than Thrift / Protocol Buffers](http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/), so I'm throwing JSON into this question as well. | I'm in the process of writing some code in an [open source project named thrift-protobuf-compare](http://code.google.com/p/thrift-protobuf-compare/) comparing between protobuf and thrift. For now it covers few serialization aspects, but I intend to cover more. The results (for [Thrift](http://eishay.blogspot.com/search/label/Thrift) and [Protobuf](http://eishay.blogspot.com/search/label/protobuf)) are discussed in my blog, I'll add more when I'll get to it.
You may look at the code to compare API, description language and generated code. I'll be happy to have contributions to achieve a more rounded comparison. |
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? | 296,650 | 61 | 2008-11-17T19:48:44Z | 675,527 | 49 | 2009-03-23T22:48:30Z | [
"java",
"python",
"performance",
"protocol-buffers",
"thrift"
] | We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:
Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?
Primarily languages will be Java, C/C++, Python, and PHP.
Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing [compressed JSON performing similar / better than Thrift / Protocol Buffers](http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/), so I'm throwing JSON into this question as well. | Latest comparison available here at the [thrift-protobuf-compare](https://github.com/eishay/jvm-serializers/wiki/) project wiki. It includes many other serialization libraries. |
how do i use python libraries in C++? | 297,112 | 8 | 2008-11-17T22:03:24Z | 297,155 | 14 | 2008-11-17T22:13:29Z | [
"c++",
"python",
"nltk"
] | I want to use the [nltk](http://nltk.sourceforge.net/index.php/Main_Page) libraries in c++.
Is there a glue language/mechanism I can use to do this?
Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.
Thanks | Although calling c++ libs from python is more normal - you can call a python module from c++ by bascially calling the python intepreter and have it execute the python source.
This is called [embedding](https://docs.python.org/2.7/extending/embedding.html)
Alternatively the [boost.python](http://www.boost.org/doc/libs/1_37_0/libs/python/doc/index.html) library makes it very easy. |
how do i use python libraries in C++? | 297,112 | 8 | 2008-11-17T22:03:24Z | 297,175 | 12 | 2008-11-17T22:18:46Z | [
"c++",
"python",
"nltk"
] | I want to use the [nltk](http://nltk.sourceforge.net/index.php/Main_Page) libraries in c++.
Is there a glue language/mechanism I can use to do this?
Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.
Thanks | You can also try the [Boost.Python](http://www.boost.org/doc/libs/1_37_0/libs/python/doc/index.html) library; which has [this capability](http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/callbacks.html). This library is mainly used to expose C++ to Python, but can be used the other way around. |
Why doesn't xpath work when processing an XHTML document with lxml (in python)? | 297,239 | 20 | 2008-11-17T22:42:58Z | 297,243 | 26 | 2008-11-17T22:45:15Z | [
"python",
"xml",
"xhtml",
"xpath",
"lxml"
] | I am testing against the following test document:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>hi there</title>
</head>
<body>
<img class="foo" src="bar.png"/>
</body>
</html>
```
If I parse the document using lxml.html, I can get the IMG with an xpath just fine:
```
>>> root = lxml.html.fromstring(doc)
>>> root.xpath("//img")
[<Element img at 1879e30>]
```
However, if I parse the document as XML and try to get the IMG tag, I get an empty result:
```
>>> tree = etree.parse(StringIO(doc))
>>> tree.getroot().xpath("//img")
[]
```
I can navigate to the element directly:
```
>>> tree.getroot().getchildren()[1].getchildren()[0]
<Element {http://www.w3.org/1999/xhtml}img at f56810>
```
But of course that doesn't help me process arbitrary documents. I would also expect to be able to query etree to get an xpath expression that will directly identify this element, which, technically I can do:
```
>>> tree.getpath(tree.getroot().getchildren()[1].getchildren()[0])
'/*/*[2]/*'
>>> tree.getroot().xpath('/*/*[2]/*')
[<Element {http://www.w3.org/1999/xhtml}img at fa1750>]
```
But that xpath is, again, obviously not useful for parsing arbitrary documents.
Obviously I am missing some key issue here, but I don't know what it is. My best guess is that it has something to do with namespaces but the only namespace defined is the default and I don't know what else I might need to consider in regards to namespaces.
So, what am I missing? | The problem is the namespaces. When parsed as XML, the img tag is in the <http://www.w3.org/1999/xhtml> namespace since that is the default namespace for the element. You are asking for the img tag in no namespace.
Try this:
```
>>> tree.getroot().xpath(
... "//xhtml:img",
... namespaces={'xhtml':'http://www.w3.org/1999/xhtml'}
... )
[<Element {http://www.w3.org/1999/xhtml}img at 11a29e0>]
``` |
Why doesn't xpath work when processing an XHTML document with lxml (in python)? | 297,239 | 20 | 2008-11-17T22:42:58Z | 297,310 | 7 | 2008-11-17T23:13:07Z | [
"python",
"xml",
"xhtml",
"xpath",
"lxml"
] | I am testing against the following test document:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>hi there</title>
</head>
<body>
<img class="foo" src="bar.png"/>
</body>
</html>
```
If I parse the document using lxml.html, I can get the IMG with an xpath just fine:
```
>>> root = lxml.html.fromstring(doc)
>>> root.xpath("//img")
[<Element img at 1879e30>]
```
However, if I parse the document as XML and try to get the IMG tag, I get an empty result:
```
>>> tree = etree.parse(StringIO(doc))
>>> tree.getroot().xpath("//img")
[]
```
I can navigate to the element directly:
```
>>> tree.getroot().getchildren()[1].getchildren()[0]
<Element {http://www.w3.org/1999/xhtml}img at f56810>
```
But of course that doesn't help me process arbitrary documents. I would also expect to be able to query etree to get an xpath expression that will directly identify this element, which, technically I can do:
```
>>> tree.getpath(tree.getroot().getchildren()[1].getchildren()[0])
'/*/*[2]/*'
>>> tree.getroot().xpath('/*/*[2]/*')
[<Element {http://www.w3.org/1999/xhtml}img at fa1750>]
```
But that xpath is, again, obviously not useful for parsing arbitrary documents.
Obviously I am missing some key issue here, but I don't know what it is. My best guess is that it has something to do with namespaces but the only namespace defined is the default and I don't know what else I might need to consider in regards to namespaces.
So, what am I missing? | [XPath considers all unprefixed names to be in "no namespace"](http://www.w3.org/TR/xpath#node-tests).
In particular the spec says:
"A QName in the node test is expanded into an expanded-name using the namespace declarations from the expression context. This is the same way expansion is done for element type names in start and end-tags except that the default namespace declared with xmlns is not used: if the QName does not have a prefix, then the namespace URI is null (this is the same way attribute names are expanded). "
See those two detailed explanations of the problem and its solution: [**here**](http://www.topxml.com/people/bosley/defaultns.asp) and [**here**](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1455253&SiteID=1). The solution is to associate a prefix (with the API that's being used) and to use it to prefix any unprefixed name in the XPath expression.
Hope this helped.
Cheers,
Dimitre Novatchev |
Create a zip file from a generator in Python? | 297,345 | 15 | 2008-11-17T23:27:03Z | 299,830 | 9 | 2008-11-18T19:23:41Z | [
"python",
"zip"
] | I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.
Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?
By zip file, I mean zip file. As supported in the Python zipfile package. | The only solution is to rewrite the method it uses for zipping files to read from a buffer. It would be trivial to add this to the standard libraries; I'm kind of amazed it hasn't been done yet. I gather there's a lot of agreement the entire interface needs to be overhauled, and that seems to be blocking any incremental improvements.
```
import zipfile, zlib, binascii, struct
class BufferedZipFile(zipfile.ZipFile):
def writebuffered(self, zipinfo, buffer):
zinfo = zipinfo
zinfo.file_size = file_size = 0
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell()
self._writecheck(zinfo)
self._didModify = True
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
self.fp.write(zinfo.FileHeader())
if zinfo.compress_type == zipfile.ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
else:
cmpr = None
while True:
buf = buffer.read(1024 * 8)
if not buf:
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC) & 0xffffffff
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
position = self.fp.tell()
self.fp.seek(zinfo.header_offset + 14, 0)
self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
``` |
Create a zip file from a generator in Python? | 297,345 | 15 | 2008-11-17T23:27:03Z | 2,734,156 | 7 | 2010-04-29T01:06:09Z | [
"python",
"zip"
] | I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.
Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?
By zip file, I mean zip file. As supported in the Python zipfile package. | I took [Chris B.'s answer](http://stackoverflow.com/questions/297345/create-a-zip-file-from-a-generator-in-python/299830#299830) and created a complete solution. Here it is in case anyone else is interested:
```
import os
import threading
from zipfile import *
import zlib, binascii, struct
class ZipEntryWriter(threading.Thread):
def __init__(self, zf, zinfo, fileobj):
self.zf = zf
self.zinfo = zinfo
self.fileobj = fileobj
zinfo.file_size = 0
zinfo.flag_bits = 0x00
zinfo.header_offset = zf.fp.tell()
zf._writecheck(zinfo)
zf._didModify = True
zinfo.CRC = 0
zinfo.compress_size = compress_size = 0
zf.fp.write(zinfo.FileHeader())
super(ZipEntryWriter, self).__init__()
def run(self):
zinfo = self.zinfo
zf = self.zf
file_size = 0
CRC = 0
if zinfo.compress_type == ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
else:
cmpr = None
while True:
buf = self.fileobj.read(1024 * 8)
if not buf:
self.fileobj.close()
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC)
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
zf.fp.write(buf)
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
zf.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
position = zf.fp.tell()
zf.fp.seek(zinfo.header_offset + 14, 0)
zf.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size))
zf.fp.seek(position, 0)
zf.filelist.append(zinfo)
zf.NameToInfo[zinfo.filename] = zinfo
class EnhZipFile(ZipFile, object):
def _current_writer(self):
return hasattr(self, 'cur_writer') and self.cur_writer or None
def assert_no_current_writer(self):
cur_writer = self._current_writer()
if cur_writer and cur_writer.isAlive():
raise ValueError('An entry is already started for name: %s' % cur_write.zinfo.filename)
def write(self, filename, arcname=None, compress_type=None):
self.assert_no_current_writer()
super(EnhZipFile, self).write(filename, arcname, compress_type)
def writestr(self, zinfo_or_arcname, bytes):
self.assert_no_current_writer()
super(EnhZipFile, self).writestr(zinfo_or_arcname, bytes)
def close(self):
self.finish_entry()
super(EnhZipFile, self).close()
def start_entry(self, zipinfo):
"""
Start writing a new entry with the specified ZipInfo and return a
file like object. Any data written to the file like object is
read by a background thread and written directly to the zip file.
Make sure to close the returned file object, before closing the
zipfile, or the close() would end up hanging indefinitely.
Only one entry can be open at any time. If multiple entries need to
be written, make sure to call finish_entry() before calling any of
these methods:
- start_entry
- write
- writestr
It is not necessary to explicitly call finish_entry() before closing
zipfile.
Example:
zf = EnhZipFile('tmp.zip', 'w')
w = zf.start_entry(ZipInfo('t.txt'))
w.write("some text")
w.close()
zf.close()
"""
self.assert_no_current_writer()
r, w = os.pipe()
self.cur_writer = ZipEntryWriter(self, zipinfo, os.fdopen(r, 'r'))
self.cur_writer.start()
return os.fdopen(w, 'w')
def finish_entry(self, timeout=None):
"""
Ensure that the ZipEntry that is currently being written is finished.
Joins on any background thread to exit. It is safe to call this method
multiple times.
"""
cur_writer = self._current_writer()
if not cur_writer or not cur_writer.isAlive():
return
cur_writer.join(timeout)
if __name__ == "__main__":
zf = EnhZipFile('c:/tmp/t.zip', 'w')
import time
w = zf.start_entry(ZipInfo('t.txt', time.localtime()[:6]))
w.write("Line1\n")
w.write("Line2\n")
w.close()
zf.finish_entry()
w = zf.start_entry(ZipInfo('p.txt', time.localtime()[:6]))
w.write("Some text\n")
w.close()
zf.close()
``` |
Dynamically update ModelForm's Meta class | 297,383 | 17 | 2008-11-17T23:44:27Z | 297,478 | 46 | 2008-11-18T00:38:08Z | [
"python",
"django",
"django-forms",
"metaprogramming",
"modelform"
] | I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from `as_p()`, `as_ul()`, etc does not reflect the updated Meta exclude.
I assume then that the html is generated when the ModelForm is created not when the `as_*()` is called. Is there a way to force the update of the HTML?
Is this even the best way to do it? I just assumed this *should* work.
Thoughts?
```
from django.forms import ModelForm
from testprogram.online_bookings.models import Passenger
class PassengerInfoForm(ModelForm):
def set_form_excludes(self, exclude_list):
self.Meta.exclude = excludes_list
class Meta:
model = Passenger
exclude = []
``` | The Meta class is used to dynamically construct the form definition - so by the time you've created the ModelForm instance, the fields not in the exclude have already been added as the new object's attributes.
The normal way to do it would be to just have multiple class definitions for each possible exclude list. But if you want the form itself to be dynamic, you'll have to create a class definition on the fly. Something like:
```
def get_form(exclude_list):
class MyForm(ModelForm):
class Meta:
model = Passenger
exclude = exclude_list
return MyForm
form_class = get_form(('field1', 'field2'))
form = form_class()
```
**UPDATE**: I just revisited this post and thought I'd post a little more idiomatic way to handle a dynamic class:
```
def PassengerForm(exclude_list, *args, **kwargs):
class MyPassengerForm(ModelForm):
class Meta:
model = Passenger
exclude = exclude_list
def __init__(self):
super(MyPassengerForm, self).__init__(*args, **kwargs)
return MyPassengerForm()
form = PassengerForm(('field1', 'field2'))
``` |
Dynamically update ModelForm's Meta class | 297,383 | 17 | 2008-11-17T23:44:27Z | 703,888 | 12 | 2009-04-01T02:54:06Z | [
"python",
"django",
"django-forms",
"metaprogramming",
"modelform"
] | I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from `as_p()`, `as_ul()`, etc does not reflect the updated Meta exclude.
I assume then that the html is generated when the ModelForm is created not when the `as_*()` is called. Is there a way to force the update of the HTML?
Is this even the best way to do it? I just assumed this *should* work.
Thoughts?
```
from django.forms import ModelForm
from testprogram.online_bookings.models import Passenger
class PassengerInfoForm(ModelForm):
def set_form_excludes(self, exclude_list):
self.Meta.exclude = excludes_list
class Meta:
model = Passenger
exclude = []
``` | Another way:
```
class PassengerInfoForm(ModelForm):
def __init__(self, *args, **kwargs):
exclude_list=kwargs.pop('exclude_list', '')
super(PassengerInfoForm, self).__init__(*args, **kwargs)
for field in exclude_list:
del self.fields[field]
class Meta:
model = Passenger
form = PassengerInfoForm(exclude_list=['field1', 'field2'])
``` |
Django Template Variables and Javascript | 298,772 | 92 | 2008-11-18T13:52:31Z | 298,793 | 131 | 2008-11-18T14:00:58Z | [
"javascript",
"python",
"django",
"google-app-engine",
"django-templates"
] | When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using `{{ myVar }}`.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in. | The `{{variable}}` is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.
Having said that, you can put this kind of substitution into your JavaScript.
```
<script type="text/javascript">
var a = "{{someDjangoVariable}}";
</script>
```
This gives you "dynamic" javascript. |
Django Template Variables and Javascript | 298,772 | 92 | 2008-11-18T13:52:31Z | 304,627 | 7 | 2008-11-20T08:19:31Z | [
"javascript",
"python",
"django",
"google-app-engine",
"django-templates"
] | When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using `{{ myVar }}`.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in. | For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.