use python / qt with cygwin
Hello, Do you know if it is possible to use python + qt bindings in cygwin ? I've looked inside kde / cygwin. There is a package named qt-gcc-3 but I did'nt find the qt bindings for python :/ Is there a way to do that ? Or am I obliged to use tkinter to make user interfaces when I'm with python / cygwin ? Regards, blureD. -- http://mail.python.org/mailman/listinfo/python-list
Re: sudo open() ? (python newbee question)
The script could be SUID Root, and you could use os.setuid immediately after having performed the task to switch to a non-priviledged user. May be a big security risk, if someone can alter the script, he gains root access to the system... [EMAIL PROTECTED] wrote: > hello, > > i am writing a python script that will be run by a non root user > the script needs to open a file in write mode that is owned by root > > file = open('/etc/apt/sources.list', 'r+') > > returns permission error > > how can i call sudo on open()? > > thanks alot > slava -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
CBFalconer wrote: > Mike Schilling wrote: >> "Mike Meyer" <[EMAIL PROTECTED]> wrote in message >>> "Mike Schilling" <[EMAIL PROTECTED]> writes: >>>> "l v" <[EMAIL PROTECTED]> wrote in message >>>>> Xah Lee wrote: >>>>> >>>>>> (circa 1996), and email should be text only (anti-MIME, circa 1995), >>>>> >>>>> I think e-mail should be text only. I have both my email and >>>>> news readers set to display in plain text only. It prevents >>>>> the marketeers and spammers from obtaining feedback that my >>>>> email address is valid. A surprising amount of information >>>>> can be obtained from your computer by allowing HTML and all >>>>> of it's baggage when executing on your computer. Phishing >>>>> comes to my mind first and it works because people click the >>>>> link without looking to see where the link really takes them. >>>> >>>> A formatting-only subset of HTML would be useful for both e-mail >>>> and Usenet posts. >>> >>> Used to be people who wanted to send formatted text via email >>> would use rich text. It never really caught on. But given that >>> most of the people sending around formatted text are using >>> point-n-click GUIs to create the stuff, the main advantage of >>> HTML - that it's easy to write by hand - isn't needed. >> >> But the other advantage, that it's an existing and popular >> standard, remains. > > However, for both e-mail and news, it is totally useless. It also > interferes with the use of AsciiArt, while opening the recipient to > the dangers above. And HTML has the tendency to make e-mail and Usenet posts unnecessarily bigger, which will continue to be a bugger until broadband links become common enough. -- Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
Mike Schilling wrote: > > I see a difference between "X would be useful for A, B, and C" and "Y will > always be the only proper way." > > Don't you? Y would not be useful because of the bandwidth it consumes, the malware it would introduce, the additional time spent focusing on the format rather than quality of the content and, frankly, because it's useless. As Rich already said, if one wants to look at neatly formatted content, one can always visit the web. Usenet is meant to be an information-sharing facility, and I cannot see *any* reason why it should be exposed to all the disadvantages stated in numerous places in thread to gain a pale "advantage" such as flashy content. We already have a World Wide Web, no need to make Usenet it's clone. -- Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
Mike Schilling wrote: > > Threaded mail-readers too, screen-based editors , spell-checkers, all > useless frills. Interestingly enough, I have explained my opinion in the part of the post you have trimmed. On the other hand, things you mentioned are far from being useless. They introduce no intrinsical slowdown due to increased bandwidth consumation, nor potential security problems. They have no downsides I can possibly think of and have many advantages. They are useful. HTML on Usenet is not. -- Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
John Bokma wrote: > > You can't be sure: errors in the handling of threads can cause a buffer > overflow, same for spelling checking :-D Yes, they can, provided they are not properly coded. However, those things only interact locally with the user and have none or very limited interaction with the user on the other side of the line. As such, they can hardly be exploitable. > Some people never use them, and hence they use memory and add risks. On a good newsreader the memory use difference should be irrelevantly small, even if one does not use the features. I would call that a nitpicky argument. Also, the risk in question is not comparable because of the reasons stated above. The kind of risk you are talking about happens with /any/ software. To stay away from that we shouldn't have newsreaders (or any other software, for that matter) in the first place. > Of course can HTML be useful on Usenet. The problem is that it will be much > more often abused instead of used. No, you missed the point. I am arguing that HTML is completely and utterly /useless/ on Usenet. Time spent for writing HTML in Usenet posts is comparable to that spent on arguing about coding style or writing followups to Xah Lee. It adds no further insight on a particular subject, but _does_ add further delays, spam, bandwidth consumation, exploits, and is generally a pain in the arse. It's redundant. -- Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
John Bokma wrote: > Ulrich Hobelmann <[EMAIL PROTECTED]> wrote: > >> John Bokma wrote: >>> http://www.phpbb.com/mods/ >> >> Great. How can I, the user, choose, how to use a mod on a given web >> server? > > Ask the admin? And that is, in your opinion, completely comparable to running your own, private client? Is the admin obliged to install the mod? Is the admin even reachable? >> What if the web server runs another board than PHPBB? > > Check if there is a mod, and ask the admin. See above. >>> Does the user want this? And with a user stylesheet you can change it >>> quite radically :-) >> >> The look, not the feel. > > Wild guess: (signed) javascript and iframes? on your local computer? > > Otherwise: fetch HTML, parse it, restructure it, and have the > application run a local webserver. Python, Perl, piece of cake. You seem to be forgetting that we are mainly talking about end users here who most probably will not have the sufficient expertise to do all that. And even if they do, it's still time consuming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
John Bokma wrote: > > so use Lynx :-) > > One forum I visit is about scorpions. And really, it talks a bit easier > about scorpions if you have an image to look at :-D. > > In short: Usenet = Usenet, and www = www. Why some people want to move > people from www to Usenet or vice versa is beyond me. If 80% of the current > Usenet users stop posting, Usenet is not going to die :-D Agreed. This is actually your first post with which content I agree totally. From your other posts I got the impression that you are one of those people that are trying to make Usenet and WWW more similar to one another. -- Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
T Beck wrote: > > Wasn't the point... I never said they were. HTML is at version 4.0(I > think?) now, AND we've added extra layers of stuff you can use > alongside of it. The internet is a free-flowing evolving place... to > try to protect one little segment like usenet from ever evolving is > just ensuring it's slow death, IMHO. > > That's all... HTML is at version 4.01 to be precise, but that is precisely off-topic. This discussion has being going on for long enough. It is held in a large crosspost to newsgroups that have nothing to do with HTML or the evolution of Usenet. The bottom line is that most Usenet users like it the way it is now, and it certainly serves it's purpose. The Web and Usenet should not mix as they are two distinct entities and merging them would lose some of their distinctive qualities, making the Internet a poorer place. I suggest letting the matter rest or taking it to a more appropriate newsgroup. -- Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: type classobj not defined?
Wesley Brooks wrote: > Dear Users, > > I'm in the process of adding assert statements to a large piece of > code to aid with bug hunting and came across the following issue; > > Using python in a terminal window you can do the following: > >> type(False) == bool > True > > I would like to check that an object is a class, here's an example: > >> class b: > def __init__(self): > self.c = 1 > def d(self): > print self.c > >> type(b) > > > But the following fails: > >> type(b) == classobj > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'classobj' is not defined You can compare it against the ClassType object located in the types module. > import types > class b: def __init__(self): self.c = 1 def d(self): print self.c > type(b) == types.ClassType True -- Denis Kasak -- http://mail.python.org/mailman/listinfo/python-list
Re: Unknown locale nb_NO ?
On Tue, 07 Dec 2004 17:06:12 +0100 Stas Z <[EMAIL PROTECTED]> wrote: > When I 'googled' for it, I saw that no_NO has become nn_NO/nb_NO. > However it strikes me as odd, that Python2.3.4 raises an exception when > querying for a valid locale. I tend to call it a bug :-( Is it valid? Have you tried "locale -a | grep nb_NO"? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb blob and binary data
On Fri, 10 Dec 2004 16:58:56 +0100 Rune Hansen <[EMAIL PROTECTED]> wrote: > I'm storing gzipped data in a MySQL blob field. I can fetch the blob and > "wb" write the data to a file. It becomes a file containg gz data. > > I can't take the same data and do anything sensible with it in python - > like say zlib.decompress(data). > > How can I convert the binary data from the blob field to the gzipped > string it was stored as (java stores the string, Pickle is not an option)? You can pass any file-like object to GzipFile class: from gzip import GzipFile from cStringIO import StringIO GzipFile(fileobj=StringIO(data)).read() -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Execute code after death of all child processes - (corrected posting)
On Sat, 25 Dec 2004 08:20:24 -0600 Jeff Epler <[EMAIL PROTECTED]> wrote: > Next, you'll want to wait for each process you started: > for current_text in texts: > os.waitpid(-1, 0) > print 'this is the end' This can eventually die with exception. The proper way is: try: while True: os.waitpid(-1, 0) except OSError, exc: if exc.errno!=errno.ECHILD: raise -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: DB-API format string conventions
On Tue, 28 Dec 2004 22:02:59 +0800 Craig Ringer <[EMAIL PROTECTED]> wrote: > I'm not actually against the number of choices available, I'm just > concerned that there is currently no _single_ choice that can be > guaranteed to work, and that it's hard to identify all styles a given > API supports. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278612 -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.islink()
On Wed, 08 Dec 2004 20:42:09 +1000 "Egor Bolonev" <[EMAIL PROTECTED]> wrote: > i want to detect "'s" Junctions are just mount points, not symbolic links. Dunno how to detect them in Windows. http://support.microsoft.com/default.aspx?scid=kb;en-us;205524 -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: os.spawnv & stdin trouble
On Tue, 11 Jan 2005 17:31:07 +0100 "Jelle Feringa // EZCT / Paris" <[EMAIL PROTECTED]> wrote: > ##I know I should be using 2.4 and os.Popen, I know, I know. > ##However, since most modules I need, I'm using 2.3 for this script There is os.popen in 2.3, as well as popen2 module. Did you mean subprocess? I guess it's ported to 2.3 too. > Here's where I run into trouble. > In my os.system version, I'm perfectly able to pipe into another file, > since the process has no real connection to python whatsoever. > Would someone be able to explain me how to do this, all the tools I'm > using for this script are unix-like tools and heavily rely on piping. os.system passes commend to shell, which handles redirect for you instead of passing '>' to xform.exe as parameter. Use os.system or subprocess (a.k.a. popen5). > program = 'xform.exe' > path = 'c:\Radiance\bin\' ^^ Syntax error here. Did you mean 'c:\\Radiance\\bin\\xform.exe'? > args = ['-t 0 8 0', 'wall0.rad', '>', 'wall0.TRANS.rad'] > os.spawnv(os.P_WAIT, path, ('xform', args)) This corresponds to c:\Radiancein\ '-t 0 8 0' wall0.rad '>' wall0.TRANS.rad' command line. > here's the cmd error message: > xform: cannot find file ">" Don't understand how you got this error having syntax error and wrong path to executable. > ##for your info I'm on win/xp, python 2.3.4 BTW, you are trying to redirect stdout. Wrong subject? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: os.spawnv & stdin trouble
On Tue, 11 Jan 2005 19:08:01 +0100 "Jelle Feringa // EZCT / Paris" <[EMAIL PROTECTED]> wrote: > Using the subprocess module, but still not making any real progress... > I'm trying to make the examples given in the __doc__ work, without any > success I'm afraid, have you had more luck with it? [...] > p = Popen("xform" + " -t 0 8 0 wallo.rad", stdout=PIPE, > shell=True).communicate()[0] > p.stdout > > p = Popen("dir" + " /w", stdout=PIPE, shell=True).communicate()[0] > p.stdout If you want passing parameters via shell (shell=True), than just use os.system. Nevertheless below is correct example of subprocess usage with stdout redirected to file: out_fp = open('wall0.TRANS.rad', 'wb') subprocess.call(['c:\\Radiance\\bin\\xform.exe', '-t', '0', '8', '0', 'wallo.rad'], stdout=out_fp) -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python.org, Website of Satan
On Fri, 14 Jan 2005 11:16:59 + Michael Hoffman <[EMAIL PROTECTED]> wrote: > from socket import gethostbyaddr, herror > > for a in xrange(256): > if a < 666-255*3: > continue > for b in xrange(256): > if a+b < 666-255*2: > continue > for c in xrange(256): > if a+b+c < 666-255: > continue > for d in xrange(256): > if a + b + c + d == 666: Certainly, it can be done more efficient: for a in xrange(256): for b in xrange(max(0, (666-255*2)-a), 256): for c in xrange(max(0, (666-255)-a-b), min(666-a-b+1, 256)): d = 666-a-b-c ... I've checked these IPs with ip2cc (which can miss entries registered last month): there are 2907248 "evil" addresses, most of them (1568430) in USA. Too many to resolve. -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: need help on generator...
On 21 Jan 2005 05:58:03 -0800 [EMAIL PROTECTED] (Joh) wrote: > i'm trying to understand how i could build following consecutive sets > from a root one using generator : > > l = [1,2,3,4] > > would like to produce : > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] >>> def consecutive_sets(l): ... for i in xrange(2, len(l)): ... for j in xrange(0, len(l)-i+1): ... yield l[j:j+i] ... >>> list(consecutive_sets([1,2,3,4])) [[1, 2], [2, 3], [3, 4], [1, 2, 3], [2, 3, 4]] -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
sre is broken in SuSE 9.2
On all platfroms \w matches all unicode letters when used with flag re.UNICODE, but this doesn't work on SuSE 9.2: Python 2.3.4 (#1, Dec 17 2004, 19:56:48) [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.compile(ur'\w+', re.U).match(u'\xe4') >>> BTW, is correctly recognize this character as lowercase letter: >>> import unicodedata >>> unicodedata.category(u'\xe4') 'Ll' I've looked through all SuSE patches applied, but found nothing related. What is the reason for broken behavior? Incorrect configure options? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: sre is broken in SuSE 9.2
On Thu, 10 Feb 2005 13:00:42 +0300 "Denis S. Otkidach" <[EMAIL PROTECTED]> wrote: > On all platfroms \w matches all unicode letters when used with flag > re.UNICODE, but this doesn't work on SuSE 9.2: > > Python 2.3.4 (#1, Dec 17 2004, 19:56:48) > [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > >>> re.compile(ur'\w+', re.U).match(u'\xe4') > >>> > > BTW, is correctly recognize this character as lowercase letter: > >>> import unicodedata > >>> unicodedata.category(u'\xe4') > 'Ll' > > I've looked through all SuSE patches applied, but found nothing > related. What is the reason for broken behavior? Incorrect configure > options? Just a bit more information. test_re.py fails in SuSE 9.2 with the following errors: Running re_tests test suite === Failed incorrectly ('(?u)\\b.\\b', u'\xc4', 0, 'found', u'\xc4') === Failed incorrectly ('(?u)\\w', u'\xc4', 0, 'found', u'\xc4') -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: sre is broken in SuSE 9.2
On 10 Feb 2005 03:59:51 -0800 "Serge Orlov" <[EMAIL PROTECTED]> wrote: > > On all platfroms \w matches all unicode letters when used with flag > > re.UNICODE, but this doesn't work on SuSE 9.2: [...] > I can get the same results on RedHat's python 2.2.3 if I pass re.L > option, it looks like this option is implicitly set in Suse. Looks like you are right: >>> import re >>> re.compile(ur'\w+', re.U).match(u'\xe4') >>> from locale import * >>> setlocale(LC_ALL, 'de_DE') 'de_DE' >>> re.compile(ur'\w+', re.U).match(u'\xe4') <_sre.SRE_Match object at 0x40375560> But I see nothing related to implicit re.L option in their patches and the sources themselves are the same as on other platforms. I'd prefer to find the source of problem. -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: sre is broken in SuSE 9.2
On Thu, 10 Feb 2005 16:23:09 +0100 Daniel Dittmar <[EMAIL PROTECTED]> wrote: > Denis S. Otkidach wrote: > > > On all platfroms \w matches all unicode letters when used with flag > > re.UNICODE, but this doesn't work on SuSE 9.2: > > I think Python on SuSE 9.2 uses UCS4 for unicode strings (as does > RedHat), check sys.maxunicode. > > This is not an explanation, but perhaps a hint where to look. Yes, it uses UCS4. But debian build with UCS4 works fine, so this is not a problem. Can --with-wctype-functions configure option be the source of problem? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: sre is broken in SuSE 9.2
On Thu, 10 Feb 2005 17:46:06 +0100 "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: > > Can --with-wctype-functions configure option be the > > source of problem? > > yes. > > that option disables Python's own Unicode database, and relies on the C > library's > wctype.h (iswalpha, etc) to behave properly for Unicode characters. this > isn't true > for all environments. > > is this an official SuSE release? do they often release stuff that hasn't > been tested > at all? Yes, it's official release: # rpm -qi python Name: python Relocations: (not relocatable) Version : 2.3.4 Vendor: SUSE LINUX AG, Nuernberg, Germany Release : 3 Build Date: Tue Oct 5 02:28:25 2004 Install date: Fri Jan 28 13:53:49 2005 Build Host: gambey.suse.de Group : Development/Languages/Python Source RPM: python-2.3.4-3.src.rpm Size: 15108594 License: Artistic License, Other License(s), see package Signature : DSA/SHA1, Tue Oct 5 02:42:38 2004, Key ID a84edae89c800aca Packager: http://www.suse.de/feedback URL : http://www.python.org/ Summary : Python Interpreter BTW, where have they found something with Artistic License in Python? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: sre is broken in SuSE 9.2
On 10 Feb 2005 11:49:33 -0800 "Serge Orlov" <[EMAIL PROTECTED]> wrote: > This thread is about problems only with LANG=C or LANG=POSIX, it's not > about other locales. Other locales are working as expected. You are not right. I have LANG=de_DE.UTF-8, and the Python test_re.py doesn't pass. $LANG doesn't matter if I don't call setlocale. Fortunately setting any non-C locale solves the problem for all (I believe) unicode character: >>> re.compile(ur'\w+', re.U).findall(u'\xb5\xba\xe4\u0430') [u'\xb5\xba\xe4\u0430'] -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: sre is broken in SuSE 9.2
On Sat, 12 Feb 2005 09:42:41 +0100 "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: > the relevant part for this thread is *locale-*. if wctype depends on > the locale, it cannot be used for generic build. (custom interpreters > are an- other thing, but they shouldn't be shipped as "python"). You are right. But isalpha behavior looks strange for me anyway: why cyrillic character '\u0430' is recognized as alpha one for de_DE locale, but is not for C? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: sre is broken in SuSE 9.2
On Fri, 11 Feb 2005 18:49:53 +0100 "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: > >> >>> re.compile(ur'\w+', re.U).findall(u'\xb5\xba\xe4\u0430') > >> [u'\xb5\xba\xe4\u0430'] > > > > I can't find the strict definition of isalpha, but I believe average > > C program shouldn't care about the current locale alphabet, so isalpha > > is a union of all supported characters in all alphabets > > btw, what does isalpha have to do with this example? The same problem is with isalpha. In most distributions: >>> for c in u'\xb5\xba\xe4\u0430': print c.isalpha(), ... True True True True And in SuSE 9.2: >>> for c in u'\xb5\xba\xe4\u0430': print c.isalpha(), ... False False False False -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it possible to use the logging-module in a threadless environment?
On 17 Feb 2005 05:41:12 -0800 [EMAIL PROTECTED] (Roger) wrote: > I'd like to use a program (roundup) that imports the logging.config > module on a machine where I could not get the thread and threading > modules to compile. > > How dangerous is it to changing /lib/python2.4/logging/config.py to > something like: > > import dummy_thread as thread, dummy_threading as threading I believe it's a bug and logging/config.py should use the same approach as logging/__init__.py do: try: import thread import threading except ImportError: thread = None -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: re.compile and very specific searches
On Fri, 18 Feb 2005 13:14:28 -0500 rbt <[EMAIL PROTECTED]> wrote: > Is it possible to use re.compile to exclude certain numbers? For > example, this will find IP addresses: > > ip = re.compile('\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}') > > But it will also find 999.999.999.999 (something which could not > possibly be an IPv4 address). Can re.compile be configured to filter > results like this out? Try this one: re.compile(r'\b%s\b' % r'\.'.join(['(?:(?:2[0-4]|1\d|[1-9])?\d|25[0-5])']*4)) -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: bsddb for k, v in db.items(): do order the numbers ?
On Mon, 28 Feb 2005 11:48:44 -0500 Christopher De Vries <[EMAIL PROTECTED]> wrote: > If you want your key, value pairs in a certain order you have to sort > them yourself. Dictionaries and bsddb keys are unsorted. You are not right, records in BTree (btopen) are certainly sorted. For positive integers you can pack keys with struct.pack('>I', value). -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Pre-PEP: Dictionary accumulator methods
On 18 Mar 2005 21:03:52 -0800 Michele Simionato wrote: MS> +1 for inc instead of count. MS> appendlist seems a bit too specific (I do not use dictionaries of MS> lists that often). inc is too specific too. MS> The problem with setdefault is the name, not the functionality. The problem with functionality: d.setdefault(k, v) can't be used as lvalue. If it could, we wouldn't need count/inc/add/tally method. MS> get_or_set would be a better name: we could use it as an alias for MS> setdefault and then remove setdefault in Python 3000. What about d.get(k, setdefault=v) alternative? Not sure whether it's good idea to overload get() method, just an idea. -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr inside a module
On Wed, 23 Mar 2005 11:35:34 +0100 kramb64 wrote: K> I'm trying to use setattr inside a module. K> >From outside a module it's easy: K> K> import spam K> name="hello" K> value=1 K> setattr(spam, name, value) K> K> But if I want to do this inside the module spam itself, what I've to K> pass to setattr as first argument? globals()[name] = value or setattr(__import__(__name__), name, value) # note, circular import here -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: need help with nullmailer-inject in python cgi script to send attachements ?
On 24 Mar 2005 05:20:06 -0800 [EMAIL PROTECTED] wrote: TC> Due to the restrictions I have at my host, I cannot use smtplib in TC> my email cgi script. They gave me a script they use that calls TC> nullmailer-inject. I am trying to figure out how to add the TC> ability to send attachments via the nullmailer-inject call. I could TC> not find much documentation on google about nullmailer. Has anyone TC> used it before to send attachments? Here is function I have so TC> far that sends a regular email. The variables like recipient are TC> set from a cgi in another part of the script. [...] TC> mailfl=os.popen('/usr/bin/nullmailer-inject -f '+fromaddr,'w') TC> mailfl.write('To: '+recipient+nl) TC> if fromaddr: mailfl.write('From: '+fromaddr+nl) TC> mailfl.write('Subject: %s%s\n\n'%(subject,uri)) TC> mailfl.write(intro) TC> rx=0 TC> prev='' TC> for x in cap: TC> while (rx if reql[rx]<>prev: TC> putln(reql[rx],mailfl) TC> rx=rx+1 TC> putln(x,mailfl) TC> prev=x TC> TC> for x in envl: TC> mailfl.write('%s: %s\n'%(x,env[x])) TC> mailfl.close() Use email package. Something like the following (untested): from email.MIMEText import MIMEText msg = MIMEText(body) msg['Subject'] = ... msg['From'] = ... msg['To'] = ... from email.MIMEBase import MIMEBase attachment = MIMEBase('application', 'octet-stream') attachment.set_payload(open(filename, 'rb').read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) from email.Encoders import encode_base64 encode_base64(attachment) msg.attach(attachment) # using popen is unsafe if we can't trust fromaddr, using subprocess from subprocess import Popen, PIPE mailfl = Popen(['/usr/bin/nullmailer-inject', '-f', fromaddr], stdin=PIPE) mailfl.stdin.write(msg.as_string()) mailfl.stdin.close() mailfl.wait() -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: embedded python example: PyString_FromString doesnt work?
On Thu, 24 Mar 2005 21:12:18 + David Harris wrote: DH> int DH> main(int argc, char *argv[]) DH> { DH> PyObject *pName, *s, *pModule, *pDict, *pFunc; DH> PyObject *pArgs, *pValue; DH> int i; DH> DH> if (argc < 3) { DH> fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); DH> return 1; DH> } DH> DH> DH> Py_Initialize(); [...] DH> Calling the program gives an error; DH> "[EMAIL PROTECTED]:~/source/python> ./test_String script1.py multiply 4 DH> 5 import went bang... DH> ImportError: No module named script1.py" DH> script1.py exists and it is in the same directory as the executable DH> so its not a path error or that kind of stuff. I believe you have to call Py_SetProgramName before Py_Initialize, or otherwise let Python know that it should look for modules in this directory. See http://python.org/doc/current/api/embedding.html#l2h-40 -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL
On Wed, 30 Mar 2005 08:33:44 -0800 (PST) suresh mathi wrote: SM> All 3 images that i try to paste are having a SM> transparent background. SM> When i try to open the image and paste the background SM> becomes black. I masked the black areas but still the SM> shape is not that clear. I had similar problems and solved them using some tricks with image.info['transparency'] and image.palette. Unfortunately I can't find this example, so if you succeed please post solution here. -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: deprecation of has_key?
On Thu, 21 Apr 2005 05:43:36 -0400 Steve Holden wrote: SH> Two words: backward compatibility. To lose that method now would SH> break thousands of existing programs. [...] SH> The method might disappear in Python 3.0, when we will be allowed to SH> break backward compatibility - you are correct in saying it's no SH> longer necessary. I believe it's a bad idea to remove this method, since behavior of both "item in dict" and "for item in dict" (especially the later) in Python does't seem sane to me. Just look at reverse operations: dict.fromkeys(seq) <-> d.keys(), d.iterkeys() - OK dict(iterable) <-> d.iteritems() - why not iter(d)? dict(l) <-> d.items() - why not list(d)? dict(seq) <-> d.keys(), d.iterkeys() - looks very strange. And those ("item in dict" and "for item in dict") are related of course, since the following should pass: for item in d: assert item in d That's the reason why I always prefer to use has_key() and iteritems() to in and iter(). Readability counts. -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: deprecation of has_key?
On Thu, 21 Apr 2005 08:50:25 -0600 Steven Bethard wrote: SB> Huh? I'm not following your logic. Why is "item in dict" less SB> readable than "dict.has_key(item)"? Something to do with expecting SB> inverses that don't exist? SB> SB> Personally, I use "item in dict" because it's quite readable to me, SB> and generally faster. For me dictionary is a collection of key-value pairs, but not a collection of keys (that's what set is). -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Can an object of a C type have random members added? tp_dictoffset?
On Thu, 21 Apr 2005 17:55:24 +1000 Gregory Bond wrote: GB> I have a class implemented in C using tp_members to specify (read-only) GB> access to data members in the C struct. I'd like to be able to do the GB> decoration trick with objects of this class. Is this possible? GB> GB> [The documentation for tp_dictoffset eseems to hint that this is GB> possible. how do I use it?] Something like the following: typedef struct { PyObject_HEAD PyObject *dict; } YourObject; static PyMemberDef module_members[] = { {"__dict__", T_OBJECT, offsetof(YourObject, dict), READONLY}, {0} }; PyObject * Your_New() { YourObject *obj; obj = PyObject_GC_New(YourObject, &Your_Type); if (obj==NUL) return NULL; obj->dict = PyDict_New(); if (obj->dict==NULL) { Py_DECREF(obj); return NULL; } PyObject_GC_Track(obj); return (PyObject *)obj; } PyTypeObject Your_Type = { PyObject_HEAD_INIT(&PyType_Type) # ...skipped... offsetof(YourObject, dict), /* tp_dictoffset */ # ...skipped... } -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib2 file upload error
On Thu, 28 Apr 2005 15:45:50 +1200 Thomas wrote: T> d = [ ('cmd', 'add-item'), T> ('protocol_version', '2.1'), T> ('userfile', open(FILE)), T> ] T> req = urllib2.Request(URL, d) [...] T> TypeError: sendall() argument 1 must be string or read-only buffer, T> not list Exactly as error message states: the second argument to Request must be string, not list. You have to encode the body manually. T> Tried the script from T> http://fabien.seisen.org/python/urllib2_multipart.html T> also T> Getting similar error.. Are you sure you imported urllib2_file? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: translating C++ exceptions to python
On 13 Jun 2005 04:23:03 -0700 [EMAIL PROTECTED] wrote: > Hi all, > > I have a C++ library I call from python. The problem is I have c++ > exceptions that i want to be translated to python. I want to be able to > do stuff like: > try: > my_cpp_function() > except cpp_exception_1: > do_stuff > except cpp_exception_2: > do_other_stuff > > any ideas how can i do the translation? 1. Create Python class for your exception. For simple case the code will be: static PyObject *YouExceptionClass; # and in module initialization function: YouExceptionClass = PyErr_NewException("YourModule.YourException", 0, 0); 2. Add it to module dictionary. 3. In wrapper for my_cpp_function use something like the following code: try { my_cpp_function_impl(); } catch (YouException &exc) { PyErr_SetString(YouExceptionClass, exc.what()); return 0; } -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to right align IPaddress?
On Fri, 17 Jun 2005 09:46:52 +0100 (BST) praba kar <[EMAIL PROTECTED]> wrote: > Is it possible to right align > the Ipaddress? Normally we can > right align the list of numbers > by %3u or %7u. How we can right > align the Ipaddress? > > I expects below format output > eg 203.199.200.0 > 203.33.20.0 >>> for ip in ('203.199.200.0', '203.33.20.0'): ... print '%15s' % ip ... 203.199.200.0 203.33.20.0 >>> for ip in ('203.199.200.0', '203.33.20.0'): ... print ip.rjust(15) ... 203.199.200.0 203.33.20.0 -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Static (why?) PyDateTimeAPI and SIP
I use datetime C API in extension module generated with SIP. But SIP break the code into several .cpp files compiled separately and PyDateTimeAPI used by all macros constituting public interface is declared static. The current solution is to define my own functions in main module as workaround: %ModuleHeaderCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs); %End %ModuleCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs) { return PyDateTime_FromDateAndTime(year, month, day, hour, minute, seconds, usecs); } // and so on for each macro used %End %PostInitialisationCode PyDateTime_IMPORT; %End But I wonder why PyDateTimeAPI is declared static, and is the a better solution? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding Python - How to create a class instance
On Sun, 19 Jun 2005 10:29:53 +0300 Miki Tebeka <[EMAIL PROTECTED]> wrote: > I'm trying to embed Python in a C application. > What I didn't find is how to create an instance once I have a class object. Class is a callable object. Just call it to create instance. > I'd like to do the equivalent of: > > from a import A > obj = A() > obj.foo(10) > > The following code omits error checking for clarity. > --- a.py --- > class A: > def foo(self, x): > print "A got %d" % x > --- a.py --- > > --- a.c --- > int > main() > { > PyObject *module, *A, *dict, *a, *args; > PyObject *obj; > > Py_Initialize(); > > PyRun_SimpleString("import sys; sys.path.append('.')"); > > module = PyImport_ImportModule("a"); > dict = PyModule_GetDict(module); > A = PyDict_GetItemString(dict, "A"); > /* FIXME: Create obj as instance of A (a = A()) */ > obj = ??? obj = PyObject_CallObject(A, NULL); > > foo = PyObject_GetAttrString(obj, "foo"); > args = Py_BuildValue("(O, i)", obj, 49); > PyObject_CallObject(foo, args); PyObject_CallMethod(obj, "foo", "i", 49); > Py_Finalize(); > > return 0; > } > --- a.c --- -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding Python - Deleting a class instance
On Tue, 21 Jun 2005 12:06:47 GMT "Bue Krogh Vedel-Larsen" <[EMAIL PROTECTED]> wrote: > How do I delete a class instance created using PyInstance_New? I've tried > calling Py_CLEAR on the instance, but __del__ isn't called. I've also tried > calling PyObject_Del, but this gives an access violation in > _PyObject_DebugDumpAddress so I guess that ain't a good idea :) It is deleted automatically when reference count become zero or when garbage collector runs if the object contains references to itself. Just call Py_DECREF on it if you are not going to use it anymore. > I've noticed that the PyObject returned by PyInstance_New has refcount = 2, > does this have any significance? The code below prints 1: PyObject *obj = PyInstance_New(PyExc_Exception, 0, 0); std::cerr << obj->ob_refcnt << "\n"; Does it create circular references in constructor? -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Re: python commmand line params from c++
On 30 Jun 2005 07:52:04 -0700 "Wesley Henwood" <[EMAIL PROTECTED]> wrote: > What is the proper way to pass command line parameters to a python > script called from C++? I'm tryng this: Have you tried PySys_SetArgv? > path = "c:\\someDir\\someScript.py param1 param2 param3"; > PyRun_SimpleFile(PyFile_AsFile( PyFile_FromString( path, "r")), > "someScript.py"); This code looks strange: you open file and create Python file object from its descriptor (PyFile_FromString), then get descripto back (PyFile_AsFile) to pass it to PyRun_SimpleFile. Why don't you just use C fopen function? > I'm getting a "format error someScript.py, line 1" when the code is > executed. > > Note: The strange appearannce of the 3 python function calls nested is > not a bug, but required to prevent a run-time error. I believe it's due to PyFile_FromString failing to open non-existent file. You must check return value of it. -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
Characters contain themselves?
While testing recursive algoritms dealing with generic lists I stumbled on infinite loops which were triggered by the fact that (at least for my version of Pyton) characters contain themselves.See session: system prompt% python Python 2.3.5 (#2, Feb 9 2005, 00:38:15) [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 'a' is 'a' True >>> 'a' in 'a' True >>> 'a' in ['a'] True >>> Leading to paradoxes and loops objects which contain themselves (and other kinds of monsters) are killed in set theory with the Axiom of Foundation:=) But let's go back to more earthly matters. I couldn't find any clue in a python FAQ after having googled with the following "Python strings FAQ" about why this design choice and how to avoid falling in this trap without having to litter my code everywhere with tests for stringiness each time I process a generic list of items. Any hints would be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Characters contain themselves?
gry@ll.mit.edu wrote: > In fact, not just characters, but strings contain themselves: > > 'abc' in 'abc' > > True > > This is a very nice(i.e. clear and concise) shortcut for: > > 'the rain in spain stays mainly'.find('rain') != -1 > > True > > Which I always found contorted and awkward. > > Could you be a bit more concrete about your complaint? > > -- George > [Thanks, I did enjoy looking up the Axiom of Foundation!] Here is the minimal context triggering an infinite descent in recursion. From the answers I've got it seems I'll have to check if I'm iterating on a string or on another kind of "list". > python Python 2.3.5 (#2, Feb 9 2005, 00:38:15) [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.setrecursionlimit(10) >>> def f(List): ... try: # assuming List supports iteration ... new=[f(item) for item in List] ... except:# if no iteration is possible ... new=1 ... return new ... >>> f([1, [2,3]]) # f substitutes each non iterable item by 1 (silly butshows >>> the problem) [1, [1, 1]] >>> f([1, [2.3, (5,6,7)]]) [1, [1, [1, 1, 1]]] >>> f('bac') 1]]], [[[1]]], [[[1 >>> sys.setrecursionlimit(5) >>> f('bac') [[[1]], [[1]], [[1]]] >>> # each item in 'bac' is a character, ie. a string of length one on wich one can iterate and so triggers an infinite descent of recursion. ... -- http://mail.python.org/mailman/listinfo/python-list