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="")
... |
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 ... |
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 = ''
... |
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
In... |
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 she... |
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.
... |
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)
```
![enter image description he... |
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)
@classmetho... |
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 ... |
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" .f... |
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? I... | 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.
... |
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? I... | 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: FROMADD... |
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 con... | 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, f... |
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+)')
>>> mat... | 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+)')
>>> mat... | 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... |
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+)')
>>> mat... | 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 crea... | 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 k... | 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... |
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 k... | 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};... |
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 k... | 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 ca... |
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
```
Thou... |
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 lang... | 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 ... |
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 lang... | "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 [WS... |
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_d... | 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 s... |
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 ve... |
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 i... | 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 i... | 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 i... | 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.IN... |
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 multi... | 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 ... |
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 multi... | 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__... |
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 multi... | 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, se... |
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 multi... | 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.in... |
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... | 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 withi... |
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... | 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, includin... |
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... | 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 exampl... |
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... | 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 ... |
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... | 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:
pri... |
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 chec... | 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 devic... |
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 chec... | 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:... |
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 chec... | ```
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 chec... | 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 !=... |
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 val... | `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 val... | 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 someFunc... |
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
.... |
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 st... |
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>
... | 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>
... | 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:
```
impo... |
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 executabl... | 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 i... |
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 go... | 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 go... | 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... |
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 ... |
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... | 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 lig... |
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... | 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-define... |
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 ... | 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 ... |
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 ... | 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_st... |
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 ... | 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 ... | 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 s... |
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 ... | 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
$ l... |
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 ... | 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, the... |
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 ... | 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 i... |
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 ... | 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... | 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&... |
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 Processo... |
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.u... |
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 w... |
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, http... |
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 ... | 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 b... |
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 ... | ```
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 ... | 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 ... |
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 ... |
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
... |
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... | 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>
> O... |
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... | 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... | 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:
`... |
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 b... | ```
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 (... |
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)
... |
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 comp... |
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, T... | 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, T... | 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... |
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, T... | 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/... |
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>
</h... | 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... |
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>
</h... | [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... |
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 ... | 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 incrementa... |
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 ... | 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(thread... |
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 ... | 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 ... |
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 ... | 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 = Pas... |
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 ... | 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 gi... |
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 ... | 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.