Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally?
I can think of at least 3 string techniques:
Classic "%" based formatting:
"My name is %(name)s" % locals()
.format() based formatting:
"My name is {name}".format( locals() )
string.Template.safe_substitute()
import string
template = string.Template( "My name is ${name}" )
template.safe_substitute( locals() )
The advantage of the string.Template technique is that a translated string with with an incorrectly spelled variable reference can still yield a usable string value while the other techniques unconditionally raise an exception. The downside of the string.Template technique appears to be the inability for one to customize how a variable is formatted (padding, justification, width, etc).
How do I find out if a connection has been broken using the httplib library? Seems like something so basic yet I can't find the answer on here or google.
Is it possible to replace the following with a list comprehension?
res = []
for a, _, c in myList:
for i in c:
res.append((a, i))
For example:
# Input
myList = [("Foo", None, [1, 2, 3]), ("Bar", None, ["i", "j"])]
# Output
res = [("Foo", 1), ("Foo", 2), ("Foo", 3), ("Bar", "i"), ("Bar", "j")]
Hello,
I am trying to understand the advantages of the module Multiprocessing over Threading. I know that Multiprocessing get's around the Global Interpreter Lock, but what other advantages are there, and can threading not do the same thing?
I know it's a really simple question, but I have no idea how to google it.
how can I do
print '<a href="%s">%s</a>' % (my_url)
So that my_url is used twice? I assume I have to "name" the %s and then use a dict in the params, but I'm not sure of the proper syntax?
just FYI, I'm aware I can just use my_url twice in the params, but that's not the point :)
Hi,
Need help regarding re.
file = 'file No.WR79050107006 from files'
So what I am trying to do is validate if file string contains WR + 11 digit.
result = re.match('^(\S| )*(?P<sr>(\d){11})(\S| )*', file)
Its validate only 11 digit but not WR before it.
How can I do that?
Using re after matching how can I get the match value ( WR79050107006)
I can do string find
index = file.find('file No.')
and then get the value of next 13 char.
thanks
i am using XML as my backend for the application...
LXML is used to parse the xml.
How can i encrypt this xml file to make sure that the data is protected......
thanks in advance.
I have a module called nbemail.py and in this module I want to use the function package_post defined in the module main.py. I am using this statement:
from api.main import package_post
But I am getting this error:
ImportError: cannot import name package_post
I really don't know why I am getting this error! I do have _init_.py files in the api directory (which contains the files nbemail.py and main.py) and I do have the function package_post defined in main.py.
Any idea to help fixing this problem?
Say I've got a list of lists. Say the inner list of three elements in size and looks like this:
['apple', 'fruit', 1.23]
The outer list looks like this
data = [['apple', 'fruit', 1.23],
['pear', 'fruit', 2.34],
['lettuce', 'vegetable', 3.45]]
I want to iterate through the outer list and cull data for a temporary list only in the case that element 1 matches some keyword (aka: 'fruit'). So, if I'm matching fruit, I would end up with this:
tempList = [('apple', 1.23), ('pear', 2.34)]
This is one way to accomplish this:
tempList = []
for i in data:
if i[1] == 'fruit':
tempList.append(i[0], i[2])
is there some 'Pythonic' way to do this in fewer lines?
Hello,
I have a script and I want one function to run at the same time as the other.
Example code I have looked at:
import threading
def MyThread ( threading.thread ):
doing something........
def MyThread2 ( threading.thread ):
doing something........
MyThread().start()
MyThread2().start()
I am having trouble getting this working. I would prefer to get this going using a threaded function rather than a class.
Thanks for any help.
I have this socket server script,
import SocketServer
import shelve
import zlib
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.words = shelve.open('/home/tipu/Dropbox/dev/workspace/search/words.db', 'r');
self.tweets = shelve.open('/home/tipu/Dropbox/dev/workspace/search/tweets.db', 'r');
param = self.request.recv(1024).strip()
try:
result = str(self.words[param])
except KeyError:
result = "set()"
self.request.send(str(result))
if __name__ == "__main__":
HOST, PORT = "localhost", 50007
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
And this receiver,
from django.http import HttpResponse
from django.template import Context, loader
import shelve
import zlib
import socket
def index(req, param = ''):
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(param)
data = zlib.decompress(s.recv(131072))
s.close()
print 'Received', repr(data)
t = loader.get_template('index.html')
c = Context({ 'foo' : data })
return HttpResponse(t.render(c))
I am sending strings to the receiver that are in the hundreds of kilobytes. I end up only receiving a portion of it. Is there a way that I can fix that so that the whole string is sent?
The users of my app can configure the layout of certain files via a format string.
For example, the config value the user specifies might be:
layout = '%(group)s/foo-%(locale)s/file.txt'
I now need to find all such files that already exist. This seems easy enough using the glob module:
glob_pattern = layout % {'group': '*', 'locale': '*'}
glob.glob(glob_pattern)
However, now comes the hard part: Given the list of glob results, I need to get all those filename-parts that matched a given placeholder, for example all the different "locale" values.
I thought I would generate a regular expression for the format string that I could then match against the list of glob results (or then possibly skipping glob and doing all the matching myself).
But I can't find a nice way to create the regex with both the proper group captures, and escaping the rest of the input.
For example, this might give me a regex that matches the locales:
regex = layout % {'group': '.*', 'locale': (.*)}
But to be sure the regex is valid, I need to pass it through re.escape(), which then also escapes the regex syntax I have just inserted. Calling re.escape() first ruins the format string.
I know there's fnmatch.translate(), which would even give me a regex - but not one that returns the proper groups.
Is there a good way to do this, without a hack like replacing the placeholders with a regex-safe unique value etc.?
Is there possibly some way (a third party library perhaps?) that allows dissecting a format string in a more flexible way, for example splitting the string at the placeholder locations?
I need to transform a list into dictionary as follows.
The odd elements has the key, and even number elements has the value.
x = (1,'a',2,'b',3,'c') - {1: 'a', 2: 'b', 3: 'c'}
def set(self, val_):
i = 0
for val in val_:
if i == 0:
i = 1
key = val
else:
i = 0
self.dict[key] = val
My solution seems to long, is there a better way to get the same results?
I want to know if there would be a way to catch exceptions inside called methods.
Example:
def foo(value):
print value
method(x)
This would throw a NameError exception, cause x is not declared.
I'd like to catch this NameError exception inside foo method.
Is there a way?
Is it possible to get reference to class B in this example?
class A(object): pass
class B(A):
def test(self):
test2()
class C(B): pass
import inspect
def test2():
frame = inspect.currentframe().f_back
cls = frame.[?something here?]
# cls here should == B (class)
c = C()
c.test()
Basically, C is child of B, B is child of A. Then we create c of type C. Then the call to c.test() actually calls B.test() (via inheritance), which calls to test2().
test2() can get the parent frame frame; code reference to method via frame.f_code;
self via frame.f_locals['self']; but type(frame.f_locals['self']) is C (of course), but not B, where method is defined.
Any way to get B?
I have a dictionary of the following form
a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
I want to sort this dictionary with respect to key as following
a = {'1':64,'6':5,'67':7,'88':3, '100':12,'test':34 }
Please help
I'm uploading potentially large files to a web server. Currently I'm doing this:
import urllib2
f = open('somelargefile.zip','rb')
request = urllib2.Request(url,f.read())
request.add_header("Content-Type", "application/zip")
response = urllib2.urlopen(request)
However, this reads the entire file's contents into memory before posting it. How can I have it stream the file to the server?
Hello everyone. I am using wxPython and Py2exe to create my application and my only problem is loading for example bitmaps.
Ok so lets say I want to add an image to my application, and thats fairly easy using wxPython, and lets say it is on the same directory of my .py so for example:
image = wx.StaticBitmap(self, -1, wx.Bitmap('image.bmp')
Now, this works obviously fine, problem is when I convert to Py2exe, I would like to use the resources from the dlls that I included in the Py2Exe compilation.
So basically what I want to do is to instead of including the images on the same folder as my application in order to work, I would like to use it from the resources so people won't see the images on the folder.
it's annoying how sqlite always returns a list of touples! i can see the why this is necessary, but when i am querying a single column, how do i get a plain list?
e.g cursor.fetchall() returns [(u'one',), (u'two',), (u'three',)]
from this, how do i get the simple list [u'one', u'two', u'three']?
Trying to convert super(B, self).method() into a simple nice bubble() call.
Did it, see below!
Is it possible to get reference to class B in this example?
class A(object): pass
class B(A):
def test(self):
test2()
class C(B): pass
import inspect
def test2():
frame = inspect.currentframe().f_back
cls = frame.[?something here?]
# cls here should == B (class)
c = C()
c.test()
Basically, C is child of B, B is child of A. Then we create c of type C. Then the call to c.test() actually calls B.test() (via inheritance), which calls to test2().
test2() can get the parent frame frame; code reference to method via frame.f_code;
self via frame.f_locals['self']; but type(frame.f_locals['self']) is C (of course), but not B, where method is defined.
Any way to get B?
I have a PSP page with html embedded. I need to place another for loop so i can insert another %s next to background-color: which will instert a appropriate colour to colour in the html table.
For example i need to insert for z in colours so it can loop over the colours list and insert the correct colour. Where ever i try to insert the for loop it doesnt seem to work it most commonly colours each cell in the table 60 times then moves onto the next cell and repeats itself and crashes my web browser.
The colours are held in a table called colours.
code below:
<table>
<%
s = ''.join(aa[i] for i in table if i in aa)
for i in range(0, len(s), 60):
req.write('<tr><td><TT>%04d</td>' % (i+1));
for k in s[i:i+60]:
req.write('<TT><td><TT><font style="background-color:">%s<font></td>' % (k));
req.write('</TT></tr>')
#end
%>
</table>
Hi all,
In the Getting things gnome code base I stumbled upon this import statement
from GTG import _
and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up.
Thank you all in advance
Paul