Fw: Query regarding Python sybase module
- Forwarded Message From: srinivasan srinivas To: [email protected] Sent: Tuesday, 24 March, 2009 7:42:35 PM Subject: Re: Query regarding Python sybase module NO. I tried with what u have mentioned in the previous update. But it gave only one result set. Thanks, Srini - Original Message From: "[email protected]" To: srinivasan srinivas Cc: [email protected] Sent: Tuesday, 24 March, 2009 6:40:37 PM Subject: Re: Query regarding Python sybase module Srini> Does Sybase Python driver module implement multiple result sets Srini> from a single command? I've used it to get multiple result sets from stored procedures, so I guess the answer would be "yes". Something like this: >>> params = curs.callproc('stored_procedure', params) >>> while True: ... rows = curs.fetchall() ... print rows ... if not curs.nextset(): ... break -- Skip Montanaro - [email protected] - http://www.smontanaro.net/ Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/ Check out the all-new Messenger 9.0! Go to http://in.messenger.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: fft of a dat file?
Hello I have not tried the code because in no part of the code is the array "out" being created. As such, it is bound to return an error that out isnt created. The point here is how i can get sampled values from the dat file which has lines like this:- \r\n i need to isolate the sampled values and put them into an array. Regards Soumen On Wed, Mar 25, 2009 at 12:15 PM, Steven D'Aprano wrote: > On Wed, 25 Mar 2009 11:26:00 +0530, Soumen banerjee wrote: > >> Hello, >> I'm kind of new to python and i wanted to do a little project, make a >> frequency plot of some wav audio. I have been following this webpage >> http://www.acronymchile.com/sigproc.html and have got to the making of a >> dat file containing the samples and time of sampling. The question here >> is how do i use FFT.fft to actually take an fft of this dat file since >> the first two lines are useless and also we have a \r\n after every >> sample. Also i would like some explanation on what FFT.fft expects as >> input. Does it expect the sampling times also or only the sampling >> values? > > > Did you follow the instructions in the webpage? I quote: > > "Analysing the Signal > This is really quite easy, assuming you have Numerical Python and the FFT > modules installed. Continuing from our last code snippet, where "out" > contains a list of the samples from our sound file, the following gives > us an FFT: > > import Numeric > import FFT > out_array=Numeric.array(out) > out_fft=FFT.fft(out) > > It is as easy as that!" > > > Have you done this? Did it work? If not, what error did you get? If it > did work, then what's the problem? > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Relative Imports, why the hell is it so hard?
On 25 Mrz., 05:56, Carl Banks wrote: > On Mar 24, 8:32 pm, Istvan Albert wrote: > > > On Mar 24, 9:35 pm, Maxim Khitrov wrote: > > > > Works perfectly fine with relative imports. > > > This only demonstrates that you are not aware of what the problem > > actually is. > > > Try using relative imports so that it works when you import the module > > itself. Now run the module as a program. The same module that worked > > fine when you imported it will raise the exception: > > PEP 366 addresses this issue. > > Not the best solution, one that still involves boilerplate, but it is > much less of a hack than your version, and at least it has the > blessing of the language designers so it won't unceremoniously break > at some point. > > Carl Banks A workaround that is hardly acceptable when we are working with / debugging 3rd party packages. Python was simpler without relative imports and occasional ambiguity resolutions by means of absolute imports. Unfortunately Brett Cannons reconstruction of import semantics comes a little late for Python 3 and I suppose we have to live with the current mess. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python have certificate?
On Mar 24, 12:50 pm, Johannes Bauer wrote: > Sebastian Bassi schrieb: > I'll hand out the "Johannes Bauer Python Certificate of Total > Awesomeness" for anyone who can write a hello world in python and hands > me $25000 in cash. $25,000?! For a certificate? You must be kidding! I can buy a Doctorate of Divinity (which should get me a jop in an Python shop) for less than a tenth of that. You really need to turn off your spam filter for a while to see how low the going price for fake qualifications are these days. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: file open fails.
Wouldn't it be easier just to avoid the windows slashes altogether and stick to the posix: title = 'c:/thesis/refined_title.txt' -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter - Multiple Tk() instances/mainloops in one process?
Gregory Sheaffer wrote: So, basically, is this a problem inherent in using Tkinter? And if so, are there any workarounds besides tying the windows to a root Tk() in the main program (Which isn't really an option the way the system is currently designed). probably, see http://wiki.tcl.tk/1527 which essentially says there's only one event loop although there is tcl threading see http://www.tcl.tk/doc/howto/thread_model.html, but I don't know if that allows multiple event loops. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python have certificate?
[email protected] wrote: On Mar 24, 12:50 pm, Johannes Bauer wrote: Sebastian Bassi schrieb: I'll hand out the "Johannes Bauer Python Certificate of Total Awesomeness" for anyone who can write a hello world in python and hands me $25000 in cash. $25,000?! For a certificate? You must be kidding! I can buy a Doctorate of Divinity (which should get me a jop in an Python shop) for less than a tenth of that. You really need to turn off your spam filter for a while to see how low the going price for fake qualifications are these days. ;) But that's how employers will know it's real. "But I paid $25k for this Steve Holden Institute of Technology certification -- I'm legitimately Supremely Certified Regarding Every Worthless Education Degree. This isn't some cheap internet Certification of Really Awesome Python skills honorific!" -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter - Multiple Tk() instances/mainloops in one process?
i havn't used tkinter for years, and can't remember a thing about it, but many gui toolkits (not just in python) manage a single event loop and need care when working with multiple threads. that doesn't mean that you cannot have multithreaded programs, but does mean that you do not invoke gui actions from the other threads. instead, typically, there is a way for other threads to deposit an "event" for the gui thread to act on. see, for example, http://docs.huihoo.com/tkinter/TkinterSummary.html#Hints where it says: All Tkinter access must be from the main thread (or, more precisely, the thread that called mainloop). Violating this is likely to cause nasty and mysterious symptoms such as freezes or core dumps. Yes this makes combining multi-threading and Tkinter very difficult. The only fully safe technique I have found is polling (e.g. use after from the main loop to poll a threading Queue that your thread writes). I have seen it suggested that a thread can safely use event_create to communicate with the main thread, but have found this is not safe. andrew Gregory Sheaffer wrote: > I've been working on a Python project for several weeks involving a client > for connecting to an AIM distribution server and holding multiple > conversations in separate windows. > > Without getting into a lot of detail, the basic main program loop is > > while(1) >on message recieved > if new conversation > create a thread for a new window instance > if old conversation > route to that window for printing > > The window instance is a Tkinter GUI class, on a basic level > self.root=Tk() > *stuff for root* > self.root.mainloop() > > All the windows involved work fine when tested individually, and when run > the system handles a single conversation and that window fine (And another > after the first has been closed). However, if at any time we attempt to > have > multiple windows (Which are in separate threads each with their own Tk() > call) the windows beyond the first fail to appear and tkinter seems to get > stuck in an infinite loop somewhere in the new mainloop() call. > > So, basically, is this a problem inherent in using Tkinter? And if so, are > there any workarounds besides tying the windows to a root Tk() in the main > program (Which isn't really an option the way the system is currently > designed). > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
[ANN] pylint 0.18 / logilab-astng 0.19 / logilab-common 0.39
-- Sylvain Thénault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations Développement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] pylint 0.18 / logilab-astng 0.19 / logilab-common 0.39
oops, forgot the mail content :$ Here it is... I'm pleased to announce releases of pylint 0.18, logilab-astng 0.19 and logilab-common 0.39. All these packages should now be cleanly available through easy install. Also, happy pylint users will get: * fixed python 2.6 support (pylint/astng tested from 2.4 to 2.6) * get source code (and so astng) for zip/egg imports * some understanding of the property decorator and of unbound methods * some false positives fixed and others minor improvments See projects home page and ChangeLog for more information: http://www.logilab.org/project/pylint http://www.logilab.org/project/logilab-astng http://www.logilab.org/project/logilab-common Please report any problem / question to the [email protected] mailing-list. Enjoy! -- Sylvain Thénault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations Développement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing frameworks
Hi Andew, > not exactly a framework, but useful while working on small projects - you > can run tests from inside eclipse (using the pydev plugin for python). > it's easy to run all tests or some small subset (although it is a bit > buggy for 3.0). What exactly is not working with 3.0? (couldn't find any related bug report on that). Cheers, Fabio -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] pylint 0.18 / logilab-astng 0.19 / logilab-common 0.39
python 3? :o) (thanks anyway - pylint is very useful, and saved me much work) Sylvain Thénault wrote: > oops, forgot the mail content :$ Here it is... > > > I'm pleased to announce releases of pylint 0.18, logilab-astng > 0.19 and logilab-common 0.39. All these packages should now be > cleanly available through easy install. > > Also, happy pylint users will get: > > * fixed python 2.6 support (pylint/astng tested from 2.4 to 2.6) > * get source code (and so astng) for zip/egg imports > * some understanding of the property decorator and of unbound methods > * some false positives fixed and others minor improvments > > See projects home page and ChangeLog for more information: > > http://www.logilab.org/project/pylint > http://www.logilab.org/project/logilab-astng > http://www.logilab.org/project/logilab-common > > Please report any problem / question to the > [email protected] > mailing-list. > > Enjoy! > -- > Sylvain Thénault LOGILAB, Paris (France) > Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations > Développement logiciel sur mesure: http://www.logilab.fr/services > Python et calcul scientifique: http://www.logilab.fr/science > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Wiki syntax available when publishing on pypi
On Tue, Mar 24, 2009 at 3:06 PM, andrew cooke wrote: > > it's some form of restructured text, which is described at > http://docutils.sourceforge.net/rst.html > > however, there seem to be various implementations; i don't know if pypi > exactly follows what is described there (i know i had a small problem with > some detail being inconsistent with that convention used in sphinx). It works! Thanks you! -- -- luca -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing frameworks
Fabio Zadrozny wrote: >> not exactly a framework, but useful while working on small projects - >> you >> can run tests from inside eclipse (using the pydev plugin for python). >> it's easy to run all tests or some small subset (although it is a bit >> buggy for 3.0). > > What exactly is not working with 3.0? (couldn't find any related bug > report on that). i don't have the project open at the moment, but iirc you cannot run all modules in a package by clicking only on the package. actually, that may be 2.6. let me check... ok, so i have a project that works with 2.6 or 3.0, and i can swap between those by selecting the appropriate interpreter in pydev's preferences (i describe this just in case it is relevant). in 3.0, i can run an individual test module (single file) by right clicking and selecting "run as..." and "python unit test". i can select all modules in a packages by shift-clicking (ie selecting all modules) and doing the same. but in 3.0 i cannot click on a package (directory), run it as a test, and so run all test modules inside the package. not even the top "src" directory. the error is: Traceback (most recent call last): File "/home/andrew/pkg/eclipse/plugins/org.python.pydev.debug_1.4.0/pysrc/runfiles.py", line 253, in PydevTestRunner(dirs, test_filter, verbosity).run_tests() File "/home/andrew/pkg/eclipse/plugins/org.python.pydev.debug_1.4.0/pysrc/runfiles.py", line 234, in run_tests files = self.find_import_files() File "/home/andrew/pkg/eclipse/plugins/org.python.pydev.debug_1.4.0/pysrc/runfiles.py", line 148, in find_import_files Finding files... os.path.walk(base_dir, self.__add_files, pyfiles) AttributeError: 'module' object has no attribute 'walk' now, in contrast, in 2.6, i can do all the above *except* intermediate packages (which may be just the way modules work in python - looks like it cannot import from unselected modules). this is with a homebuilt 3.0 - Python 3.0 (r30:67503, Jan 16 2009, 06:50:19) and opensuse's default 2.6 - Python 3.0 (r30:67503, Jan 16 2009, 06:50:19) - on Eclipse 3.3.2 with pydev 1.4.0 sorry for not reporting a bug - i assumed you'd know (and the workarounds described above meant i wasn't stalled). i also have eclipse 3.4.2 with pydev 1.4.4.2636 on a separate machine (ie new versions), and i can try there if you want (it will take a while to get the source there, but is not a problem). andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing frameworks
copy+paste error; the correct Python2.6 details are: Python 2.6 (r26:66714, Feb 3 2009, 20:49:49) andrew cooke wrote: > this is with a homebuilt 3.0 - Python 3.0 (r30:67503, Jan 16 2009, > 06:50:19) and opensuse's default 2.6 - Python 3.0 (r30:67503, Jan 16 2009, > 06:50:19) - on Eclipse 3.3.2 with pydev 1.4.0 -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing frameworks
In unittest, has anyone used the *NIX command "find" to automatically build a test suite file of all tests under a specified directory? I generally name my tests as _Test_ORIGINAL_MODULE_NAME.py where ORIGINAL_MODULE_NAME is the obvious value. This way, I can include/ exclude them from deployments, etc. in my Makefile based on filename patterns. I was thinking of doing something with "find" to get a list of test file names and then run them through a Python script to produce a top-level suite file, probably as the first step in my Makefile test target. Any thoughts? -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] pylint 0.18 / logilab-astng 0.19 / logilab-common 0.39
Le Wednesday 25 March 2009 11:58:37 andrew cooke, vous avez écrit : > python 3? :o) python 3 support is no much far away now that we support the new _ast module. logilab-common already has its py3k branch in the source repository... So it's in the plan, but any helps appreciated of course ;) -- Sylvain Thénault LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations Développement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Python 2.6.1 vs 2.6 & pyWin32
On 25/03/2009 11:06 AM, John Machin wrote: It would appear that the safest cover-most-bases option for a developer/packager of pure-Python packages (especially one intended to be runnable on older versions of Python, some as far back as 2.1) is to use Python 2.5 to make the bdist_wininst (the exe is linked against msvcr71.dll which is widely available and doesn't have SxS problems). Hi John, Note that fairly recently (IIRC, 2.6.2/3.1), the bdist_wininst stub installers moved to linking the CRT statically, so should avoid this problem. Indeed, if you use the correct magic, you should be able to use this version of distutils to build binaries for much earlier versions of Python and to allow the installer itself for that version to avoid depending on any msvcrt... Cheers, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: script files with python (instead of tcsh/bash)?
Hello David,
R. David Murray wrote:
Esmail wrote:
Here's a more Pythonic way to do that:
with open('somefile') as f:
for line in f:
if 'somestring' in line:
#do something
In other words, you don't have to read the lines into a list first if all
you are going to do is iterate through them.
Cool .. stored away for future reference.
In this case I believe I needed the contents in a list because the line
I was looking for was above one that I could easily identify. Ie, once
I had the index, I could go back/up one index to find the line I needed
to process.
(The 'with' clause closes
the file at block exit...which is overkill if this is all the program
is doing since the file will be closed at program termination anyway,
but is a good habit to get in to.)
thanks for reminding me about the 'with' clause. I agree with closing
files and in general being mindful about allocated resources.
Cheers,
Esmail
--
http://mail.python.org/mailman/listinfo/python-list
Does __init__ of subclass need the same argument types as __init__ of base class?
I do more or less understand this error message: >>> import datetime >>> x1 = datetime.date.today() >>> x2 = datetime.date(x1) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required I don't understand at all why I get the same message with this little script: import datetime class meindatum(datetime.date): def __init__(self, datum): print "meindatum" datetime.date.__init__(self, datum.year, datum.month, datum.day) # Using super() doesn't make a difference: # super(meindatum, self).__init__(self, datum.year, datum.month, #datum.day) x1 = datetime.date.today() print repr(x1) x2 = meindatum(x1) print repr(x2) ### Executing this from the command line: s...@elend:~> python /windows/E/LinWin/Python/datum_ableiten.py datetime.date(2009, 3, 25) Traceback (most recent call last): File "/windows/E/LinWin/Python/datum_ableiten.py", line 12, in x2 = meindatum(x1) TypeError: an integer is required s...@elend:~> The print command inside the __init__ method isn't executed, so that method doesn't seem to start at all. Looks to me as if meindatum.__init__() needs the same arguments as datetime.date.__init__() does, but I can't really believe that (Python isn't Pascal). Using Python 2.6.1, tried this on Linux and Windows XP. Thank you for explanations, Sibylle -- http://mail.python.org/mailman/listinfo/python-list
Re: Does __init__ of subclass need the same argument types as __init__ of base class?
Sibylle Koczian a écrit : (snip) I don't understand at all why I get the same message with this little script: import datetime class meindatum(datetime.date): def __init__(self, datum): print "meindatum" datetime.date.__init__(self, datum.year, datum.month, datum.day) x1 = datetime.date.today() print repr(x1) x2 = meindatum(x1) print repr(x2) ### Executing this from the command line: s...@elend:~> python /windows/E/LinWin/Python/datum_ableiten.py datetime.date(2009, 3, 25) Traceback (most recent call last): File "/windows/E/LinWin/Python/datum_ableiten.py", line 12, in x2 = meindatum(x1) TypeError: an integer is required s...@elend:~> The print command inside the __init__ method isn't executed, so that method doesn't seem to start at all. this often happens with (usually C-coded) immutable types. The initializer is not called, only the "proper" constructor (__new__). The following should work (not tested): class Meindatum(datetime.date): def __new__(self, datum): print "meindatum" return datetime.date(datum.year, datum.month, datum.day) HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3 consistency proposal
Ben Finney a écrit : Steven D'Aprano writes: If you *are* willing to do the work, the chances would still be pretty slim. Guido has just rejected a patch adding PEP 8 compliant aliases for types like datetime […] As Guido has quoted before, "A foolish consistency is the hobgoblin of little minds". Indeed, that quote is prominent in PEP 8 itself. gert writes: Not that I can't live without, but I am just wondering why they did not [name built-in types consistently with other classes] in the first place? Because, in the first place, built-in types were disjoint from user-defined classes. The latter could not derive from the former, and it was helpful to know the difference. The reason no longer exists (since built-in types and user types are now in a unified hierarchy), but the difference is well entrenched now and I personally see little benefit in changing it. Also and FWIW, since there's no functional nor syntaxical differences between a call to a function returning an object and a call to a class, if we where to rename anything, it would be better to drop the MixedCase convention for classes and rename *all* types to all_lower. That way, you can safely rewrite a class as a factory function (or a factory function as a class) without having to choose between breaking the API or violating pep08 !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: script files with python (instead of tcsh/bash)?
Esmail wrote:
> Hello David,
>
> R. David Murray wrote:
>> Esmail wrote:
>>
>> Here's a more Pythonic way to do that:
>>
>> with open('somefile') as f:
>> for line in f:
>> if 'somestring' in line:
>> #do something
>>
>> In other words, you don't have to read the lines into a list first if all
>> you are going to do is iterate through them.
>
> Cool .. stored away for future reference.
>
> In this case I believe I needed the contents in a list because the line
> I was looking for was above one that I could easily identify. Ie, once
> I had the index, I could go back/up one index to find the line I needed
> to process.
Here's one way to avoid the list:
last_line = None
for line in f:
if "somestring" in line and last_line is not None:
# do something with last_line
last_line = line
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: script files with python (instead of tcsh/bash)?
Peter Otten wrote: In this case I believe I needed the contents in a list because the line I was looking for was above one that I could easily identify. Ie, once I had the index, I could go back/up one index to find the line I needed to process. Here's one way to avoid the list: last_line = None for line in f: if "somestring" in line and last_line is not None: # do something with last_line last_line = line Peter yup .. this will come in handy in case the file is too big and or really needn't be all in memory. cool. thanks! Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3 consistency proposal
gert wrote: Rename all built in classes with a capital letter example Str() Int() Object() Make () optional for a function definition class Test: pass def test: pass Any chance Guido would approve this :-) Zero. But I like the idea. Is version 3 really sacrosanct? I wonder how much it's used so far. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Python 2.6.1 vs 2.6 & pyWin32
On 25/03/2009 10:32 PM, Mark Hammond wrote: On 25/03/2009 11:06 AM, John Machin wrote: It would appear that the safest cover-most-bases option for a developer/packager of pure-Python packages (especially one intended to be runnable on older versions of Python, some as far back as 2.1) is to use Python 2.5 to make the bdist_wininst (the exe is linked against msvcr71.dll which is widely available and doesn't have SxS problems). Hi John, Note that fairly recently (IIRC, 2.6.2/3.1), the bdist_wininst stub installers moved to linking the CRT statically, so should avoid this problem. Hi Mark, Indeed, if you use the correct magic, you should be able to use this version of distutils to build binaries for much earlier versions of Python and to allow the installer itself for that version to avoid depending on any msvcrt... This all sounds good. I presume that "this version of distutils" means the 2.6.2/3.1 version. In the meantime, until 2.6.2 final is released, is my suggestion of using Python 2.5 to build installers reasonable? Is there a better approach? BTW, the user with the problem has not only confirmed that he did indeed receive the misspelled German version of the error message :-) but also has successfully installed the package using a 2.5-built installer that I provided. It's curious that out of over 250 downloads of the 2.6-built installer, there's been only 1 report of the installer not working. Comments? Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] pylint 0.18 / logilab-astng 0.19 / logilab-common 0.39
Sylvain Thénault wrote: Le Wednesday 25 March 2009 11:58:37 andrew cooke, vous avez écrit : python 3? :o) python 3 support is no much far away now that we support the new _ast module. logilab-common already has its py3k branch in the source repository... So it's in the plan, but any helps appreciated of course ;) Not Found The requested URL /pub/pylint/pylint-0.18.0.tar.gz was not found on this server. Apache/2.2.9 (Debian) mod_ssl/2.2.9 OpenSSL/0.9.8g Server at ftp.logilab.org Port 80 -- http://mail.python.org/mailman/listinfo/python-list
Re: Async serial communication/threads sharing data
On Tue, 24 Mar 2009 22:20:49 -0700, John Nagle wrote: Jean-Paul Calderone wrote: On Mon, 23 Mar 2009 05:30:04 -0500, Nick Craig-Wood wrote: Jean-Paul Calderone wrote: [snip] After bringing in all the heavy machinery of Twisted, you're still polling at 10Hz. That's disappointing. Hmm, no? There's no polling in the latest version of the code I saw. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python have certificate?
-- Forwarded message -- From: Christiaan Putter Date: 2009/3/25 Subject: Re: Does Python have certificate? To: Tim Chase Come now guys, don't be so harsh. Certification is really important. Without My Crappy Software Degree my boss wouldn't have thought I'd be able to surf the internet, trolling mailing lists to scout for other highly certified programming whores. Anyone looking for a job by the way? All you need's good hair and some fancy paper with your name on it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python have certificate?
Christiaan Putter wrote: > Certification is really important. Â Without My Crappy Software Degree > my boss wouldn't have thought I'd be able to surf the internet, > trolling mailing lists to scout for other highly certified programming > whores. apologies, this is way off-topic, but kind-of related. i moved to chile from the uk about 10 years ago and needed to apply for a visa so that i could work (found a job doing j2ee). unfortunately they needed evidence of a professional qualification. now i have no professional qualification for programming, but do have a phd in astronomy, so i took the graduation certificate along to the office. my spanish is not that great (and was worse then), and the person in the office didn't seem to understand much english, but saw the paper with "doctor of philosophy" printed on it (which is what phd stands for of course) and decided i was a philosopher. so i am officially registered as a philosopher. and that apparently means i can have a programming job... no, i don't understand either :o) anyway, enough chat. better get back to philosophizing about some database queries that don't seem to be using their indices... andrew -- http://mail.python.org/mailman/listinfo/python-list
Leo 4.6 beta 1 released
Leo 4.6 b1 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.6: -- - Leo now requires Python 2.4 or later. - A new qt gui plugin, supporting Qt's look and feel. - New --config --file and --gui command-line options. - Dozens of small improvements and bug fixes. Links: -- Leo: http://webpages.charter.net/edreamleo/front.html Forum:http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward K. Ream email: [email protected] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-list
How can I know if a date is prior to today?
Hi,
I have a date expressed in seconds.
I'd want to pretty print it as "%H:%M" if the time refers to today and
"%b%d" (month, day) if it's of yesterday or before.
I managed to do that with the code below but I don't like it too much.
Is there a better way to do that?
Thanks in advance.
import time
today_day = time.strftime("%d", time.localtime(time.time()))
mytime = time.localtime(time.time() - (60*60*30)) # dummy time prior
to today
if time.strftime("%d", mytime) == today_day:
print time.strftime("%H:%M", mytime)
else:
print time.strftime("%b%d", mytime)
--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
--
http://mail.python.org/mailman/listinfo/python-list
Re: How can I know if a date is prior to today?
On Mar 25, 8:31 am, "Giampaolo Rodola'" wrote: > Hi, > I have a date expressed in seconds. > I'd want to pretty print it as "%H:%M" if the time refers to today and > "%b%d" (month, day) if it's of yesterday or before. > Use datetime module. import time from datetime import datetime now = time.time() thisTimeYesterday = now - 24*3600 print datetime.fromtimestamp(now) < datetime.today() print datetime.fromtimestamp(thisTimeYesterday) < datetime.today() -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3143: Standard daemon process library
Ben Finney writes: > I've submitted PEP 3143 > http://www.python.org/dev/peps/pep-3143/> to meet this need, > and have re-worked an existing library into a new ‘python-daemon’ > http://pypi.python.org/pypi/python-daemon/> library, the > reference implementation. > > Now I need wider testing and scrutiny of the implementation and > specification. Thank you to those who have submitted bug reports so far. I have addressed some bugs and uploaded version 1.4.4 of ‘python-daemon’ to PyPI. Changes include: * Catch and report some OSError exceptions thrown by various steps. * Wait until later in the daemonisation process to cloase all open file descriptors. This gives a chance to see errors reported earlier in the process! * Redirect standard streams to the null device if no stream specified. Testing and feedback is still welcome, I want to knock this PEP and implementation into better shape. -- \ “I have never imputed to Nature a purpose or a goal, or | `\anything that could be understood as anthropomorphic.” —Albert | _o__)Einstein, unsent letter, 1955 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I know if a date is prior to today?
I have a date expressed in seconds.
I'd want to pretty print it as "%H:%M" if the time refers to today and
"%b%d" (month, day) if it's of yesterday or before.
I managed to do that with the code below but I don't like it too much.
Is there a better way to do that?
Thanks in advance.
import time
today_day = time.strftime("%d", time.localtime(time.time()))
mytime = time.localtime(time.time() - (60*60*30)) # dummy time prior
to today
if time.strftime("%d", mytime) == today_day:
print time.strftime("%H:%M", mytime)
else:
print time.strftime("%b%d", mytime)
Well, date/datetime objects are directly comparable:
import datetime
today_day = datetime.date.today()
other = datetime.datetime.fromtimestamp(your_timestamp)
if other.date() == today_day:
fmt = "%H:%M"
else:
fmt = "%b%d"
print other.strftime(fmt)
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: fft of a dat file?
Soumen banerjee wrote:
> Hello
> I have not tried the code because in no part of the code is the array
> "out" being created. As such, it is bound to return an error that out
> isnt created. The point here is how i can get sampled values from the
> dat file which has lines like this:-
>
>\r\n
>
> i need to isolate the sampled values and put them into an array.
Maybe something like:
samples = []
with open('myfile') as f:
for line in f:
time, value = line.strip().split()
samples.append([float(time), float(value)])
Modify as appropriate to your actual needs.
--
R. David Murray http://www.bitdance.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problem in ucs4
On Mar 24, 4:55 am, "Martin v. Löwis" wrote: > > So, both Py_UNICODE and wchar_t are 4 bytes and since it contains 3 > > \0s after a char, printf or wprintf is only printing one letter. > > No. printf indeed will see a terminating character. However, wprintf > should correctly know that a wchar_t has four bytes per character, > and print it correctly. Make sure to use %ls to print wchar_t arrays; > %s would print multi-byte character strings. > > > I need to further process the data and those libraries will need the > > data in UCS2 format (2 bytes), otherwise they fail. > > Are you absolutely sure about that? Why does that library expect > UCS-2, when you system's wchar_t is four bytes? > > In any case, do what MAL told you: use the UCS-2 codec to convert > the Unicode string to a 2-bytes-per-char byte string. The PyObject > you get from the conversion is a byte string object; use > PyString_AsStringAndSize to get to the actual bytes. > > Regards, > Martin Thanks Marc and Martin, my preliminary trials are showing positive results with this method. - Abhigyan -- http://mail.python.org/mailman/listinfo/python-list
integrate does not work anymore
Hello, some time ago I implemented a Python script, which uses integrate.quad (...). This was done with Python 2.4 / Win2000. I'm working with Python 2.5 now, and installed Numpy, Scipy and Matplotlib. My script and also the test described below do not work anymore: from pylab import * from numpy import * from scipy import * from math import * m = 5 n = 3 f = lambda x:m*x+n x0 = 2.0 x1 = 6.5 res = integrate.quad(func=f, a=x0, b=x1) > Traceback (most recent call last): File "", line 1, in res = integrate.quad(func=f, a=x0, b=x1) NameError: name 'integrate' is not defined What's wrong here? Regards, Doerte -- http://mail.python.org/mailman/listinfo/python-list
*args question
Given the following code...
#!/usr/bin/env python
import time
import thread
def myfunction(string,sleeptime,*args):
while 1:
print string
time.sleep(sleeptime) #sleep for a specified amount of time.
if __name__=="__main__":
thread.start_new_thread(myfunction,("Thread No:1",2))
while 1:pass
Taken from following URL
http://linuxgazette.net/107/pai.html
How can myfunction() extract the tuple ("Thread No:1",2) from
start_new_thread() if myfunction is only being passed the single arg
("Thread No:1",2)
--
http://mail.python.org/mailman/listinfo/python-list
Re: *args question
On Mar 25, 7:05 am, grocery_stocker wrote:
> Given the following code...
>
> #!/usr/bin/env python
>
> import time
> import thread
>
> def myfunction(string,sleeptime,*args):
> while 1:
>
> print string
> time.sleep(sleeptime) #sleep for a specified amount of time.
>
> if __name__=="__main__":
>
> thread.start_new_thread(myfunction,("Thread No:1",2))
>
> while 1:pass
>
> Taken from following URLhttp://linuxgazette.net/107/pai.html
>
> How can myfunction() extract the tuple ("Thread No:1",2) from
> start_new_thread() if myfunction is only being passed the single arg
> ("Thread No:1",2)
The only thing that I think of is that the tuple ("Thread No:1",2) is
somehow being extract before it gets passed to myfunction(). Ie,
something like the following...
[cdal...@localhost ~]$ python
Python 2.4.3 (#1, Oct 1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def myfunction(first, second, *args):
... print "The formal args are: ", args
... print "the first value is:", first
... print "the second value is:", second
...
>>> a, b = (1,2)
>>> myfunction(a,b)
The formal args are: ()
the first value is: 1
the second value is: 2
--
http://mail.python.org/mailman/listinfo/python-list
Re: How can I know if a date is prior to today?
On 25 Mar, 14:51, Tim Chase wrote:
> > I have a date expressed in seconds.
> > I'd want to pretty print it as "%H:%M" if the time refers to today and
> > "%b%d" (month, day) if it's of yesterday or before.
>
> > I managed to do that with the code below but I don't like it too much.
> > Is there a better way to do that?
> > Thanks in advance.
>
> > import time
>
> > today_day = time.strftime("%d", time.localtime(time.time()))
> > mytime = time.localtime(time.time() - (60*60*30)) # dummy time prior
> > to today
> > if time.strftime("%d", mytime) == today_day:
> > print time.strftime("%H:%M", mytime)
> > else:
> > print time.strftime("%b%d", mytime)
>
> Well, date/datetime objects are directly comparable:
>
> import datetime
> today_day = datetime.date.today()
> other = datetime.datetime.fromtimestamp(your_timestamp)
> if other.date() == today_day:
> fmt = "%H:%M"
> else:
> fmt = "%b%d"
> print other.strftime(fmt)
>
> -tkc
Thanks, it did the job.
--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
--
http://mail.python.org/mailman/listinfo/python-list
Re: integrate does not work anymore
Doerte wrote: > from pylab import * > from numpy import * > from scipy import * > from math import * Don't do this, read the style guide on writing Python code. > res = integrate.quad(func=f, a=x0, b=x1) [...] > NameError: name 'integrate' is not defined # try this instead from scipy import integrate Note that this is also mentioned on the scipy homepage in their script, though they also commit the sin of namespace pollution by importing with wildcards. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
Another form of dynamic import
Hello, In short I would like to know if somebody knows if it is possible to re-execute a statement that raised an exception? I will explain the reason by providing a small introduction on why this might be nice in my case and some example code. I am using the python bindings to a *very* large C++ library. About 5000 classes divided over approx. 450 different packages are exposed through the Python interface. To reduce the number of import statements that need to be inserted and to limit the number of wildcard imports it would be very helpful if class names could be automatically imported from the proper module. There is no problem in finding out the proper module given a (valid) class name. As an example, look at the following statement >> aPoint = gp_Pnt(1.0, 0.0, 0.0) # Oops, this will raise a NameError, since # gp_Pnt class is unknown NameError: name 'gp_Pnt' is not defined As indicated, this will raise a NameError exception. What I would like to do is something like the following (pseudo-code): try: aPoint = gp_Pnt(1.0, 0.0, 0.0)[1] except NameError, e: name = e.args[0].split[1] if isValid(name): doImport(name) ===> Can I go back to statement [1] from this point? else: raise e There is no problem in catching the exception, finding out which name is unknown to python and check if this is a valid name for my library. My question is, is there any possibility of going back to the statement that raised the error, re-execute the statement and continue? Thanks for any thoughts and suggestions. Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: blocked on futex
In article <5cffe00b-2cd3-45dc-a674-87466e8ff...@f19g2000vbf.googlegroups.com>, msoulier wrote: >On Mar 20, 10:22=A0am, [email protected] (Aahz) wrote: >> >> Have you tried dumping core and using gdb to find out more about the >> process state? > >Yeah, just did. I need the debuginfo for proper symbols, but here's an >initial backtrace. > >#0 0x0084d7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2 >#1 0x009dbc1f in sem_w...@glibc_2.0 () from /lib/tls/libpthread.so.0 >#2 0x00a7ce1e in PyThread_acquire_lock () from /usr/lib/ >libpython2.3.so.1.0 >#3 0x00a7ff07 in _PyObject_GC_Del () from /usr/lib/libpython2.3.so. >1.0 >#4 0x00a29991 in PyCFunction_Call () from /usr/lib/libpython2.3.so. >1.0 >#5 0x00a5c51c in _PyEval_SliceIndex () from /usr/lib/libpython2.3.so. >1.0 [...] >#53 0x00a5d98b in _PyEval_SliceIndex () from /usr/lib/libpython2.3.so. >1.0 >#54 0x00a5e0a6 in PyEval_EvalCodeEx () from /usr/lib/libpython2.3.so. >1.0 >#55 0x00a5e36d in PyEval_EvalCode () from /usr/lib/libpython2.3.so.1.0 >#56 0x00a77827 in PyErr_Display () from /usr/lib/libpython2.3.so.1.0 >#57 0x00a78952 in PyRun_SimpleFileExFlags () from /usr/lib/ >libpython2.3.so.1.0 >#58 0x00a799a4 in PyRun_AnyFileExFlags () from /usr/lib/ >libpython2.3.so.1.0 >#59 0x00a7e69e in Py_Main () from /usr/lib/libpython2.3.so.1.0 >#60 0x080485b2 in main () > >It looks to me like it's blocking in pthread_mutex_lock, synchronizing >on a critical section for thread safety. Looks like a bug to me. I >went to report it, but there's no 2.3 version in the python bug >tracker so I'm assuming it's no longer supported. That's a bit bizarre. You're correct that if this is a Python bug, there will be no fixes available. However, you said earlier that this is a patched Python, so I'm wondering whether the applied patch is broken. Assuming I'm reading this correctly, it's hanging when trying to emit a top-level exception using PyErr_Display. At this point, I would continue watching core dumps and seeing whether _PyObject_GC_Del and/or PyErr_Display are always in the stack trace. You might also write your own top-level exception handler that logs to a file. -- Aahz ([email protected]) <*> http://www.pythoncraft.com/ "At Resolver we've found it useful to short-circuit any doubt and just refer to comments in code as 'lies'. :-)" --Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22 -- http://mail.python.org/mailman/listinfo/python-list
Problems with threaded Hotkey application
A window comes up saying "hotkeyapp has stopped working." How do I get in there to "move the RegisterHotKey line to within the thread's run method," etc.? Im trying to do this myself and not pay Acer tech support. Thanks, Anita Whitney-- http://mail.python.org/mailman/listinfo/python-list
What way is the best to check an empty list?
For ex: to check list 'A' is empty or not.. if A == []: if A.count == 0: if len(A) == 0: if not A: Thanks, Srini Add more friends to your messenger and enjoy! Go to http://messenger.yahoo.com/invite/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I know if a date is prior to today?
On Mar 26, 12:51 am, Tim Chase wrote:
> > I have a date expressed in seconds.
> > I'd want to pretty print it as "%H:%M" if the time refers to today and
> > "%b%d" (month, day) if it's of yesterday or before.
>
> > I managed to do that with the code below but I don't like it too much.
> > Is there a better way to do that?
> > Thanks in advance.
>
> > import time
>
> > today_day = time.strftime("%d", time.localtime(time.time()))
> > mytime = time.localtime(time.time() - (60*60*30)) # dummy time prior
> > to today
> > if time.strftime("%d", mytime) == today_day:
> > print time.strftime("%H:%M", mytime)
> > else:
> > print time.strftime("%b%d", mytime)
>
> Well, date/datetime objects are directly comparable:
>
> import datetime
> today_day = datetime.date.today()
> other = datetime.datetime.fromtimestamp(your_timestamp)
> if other.date() == today_day:
> fmt = "%H:%M"
> else:
> fmt = "%b%d"
> print other.strftime(fmt)
>
> -tkc
time tuples are directly comparable, too:
import time
today_day = time.localtime(time.time())[:3]
other = time.localtime(your_timestamp)
if other[:3] == today_day:
etc
etc
Cheers,
John
--
http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
On Wed, Mar 25, 2009 at 3:38 PM, srinivasan srinivas wrote: > > For ex: to check list 'A' is empty or not.. > if A == []: > if A.count == 0: > if len(A) == 0: > if not A: I would go for the last one, because it has the highest likelihood of doing what is intended when fed with something that is 'list-like' rather than a list. The second one is incorrect, by the way. A.count is something completely different. -- André Engels, [email protected] -- http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
srinivasan srinivas wrote: For ex: to check list 'A' is empty or not.. if A == []: if A.count == 0: if len(A) == 0: if not A: "if not A" -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
srinivasan srinivas: > For ex: to check list 'A' is empty or not.. Empty collections are "false": if somelist: ... # somelist isn't empty else: ... # somelist is empty Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
On Mar 26, 1:38 am, srinivasan srinivas wrote: Depends on what you mean by "best"; like graduation day at kindergarten, everyone gets a prize: > For ex: to check list 'A' is empty or not.. > if A == []: most obviously correct > if A.count == 0: best use of imagination > if len(A) == 0: best use of a built-in function > if not A: most Pythonic, most laconic, fastest -- http://mail.python.org/mailman/listinfo/python-list
Re: Does __init__ of subclass need the same argument types as __init__ of base class?
Bruno Desthuilliers writes: >> The print command inside the __init__ method isn't executed, so that >> method doesn't seem to start at all. > > this often happens with (usually C-coded) immutable types. The > initializer is not called, only the "proper" constructor (__new__). More specifically, __init__ is called, but only after __new__ has finished, and __new__ gets the arguments passed in the constructor expression. Since __new__ raises an exception for those arguments, __init__ is never reached. The fix is in such cases is, as you point out, to override __new__ and not bother with __init__ at all. -- http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
i will go against the grain slightly and say that "len" is probably the best compromise in most situations (although i admit i don't know what count is) because i think it will work when you expect it to and break when you have a bug in your program. using a simple boolean is more robust (and what i typically do in my own code because i am often too lazy to think carefully), but if it is given something that is not "list-like" you won't get an error until later in your code (and typically the sooner an error is found, the better). but i may be wrong - are there any containers (apart from pathological hand-crafted examples) that would not define __len__()? andrew srinivasan srinivas wrote: > > For ex: to check list 'A' is empty or not.. > if A == []: > if A.count == 0: > if len(A) == 0: > if not A: > > Thanks, > Srini > > > Add more friends to your messenger and enjoy! Go to > http://messenger.yahoo.com/invite/ > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
py2exe - win32com - GetGeneratePath Error
Has anyone solved the GetGeneratePath Error?
I am getting this when I use
win32com.client.DispatchWithEvents('iTunes.Application', customEventHandler). I
have drilled down to the file and found it in that path.
Does anyone have any ideas?
HERE IS THE ERROR. If anyone is good at this please email me back.
---
Traceback (most recent call last):
File "AppleHackGUI.pyw", line 376, in
File "Main.pyc", line 29, in __init__
File "win32com\client\__init__.pyc", line 250, in DispatchWithEvents
File "win32com\client\gencache.pyc", line 520, in EnsureModule
File "win32com\client\gencache.pyc", line 287, in MakeModuleForTypelib
File "win32com\client\makepy.pyc", line 256, in GenerateFromTypeLibSpec
File "win32com\client\gencache.pyc", line 141, in GetGeneratePath
IOError: [Errno 2] No such file or directory:
'C:\\Users\\Neech\\Documents\\PythonProjects\\AppleHack\\src\\dist\\library.zip\\win32com\\gen_py\\__init__.py'
-
Thanks,
Neech --
http://mail.python.org/mailman/listinfo/python-list
Debugging in Py
I'm just wondering if you all have any resources on Debugging that you all would "recommend." Due to the fact I'm doing some debugging as a beginner and this has the best of me, and I'm looking at trying to learn more about what and how to debug within Py using print, and etc... There is so much out there in Google, I have a hard time on figuring out where I should go and what I should be reading, because I been trying everything under the sun, and seems I'm at a loss here. So hopefully some of you can shed some light. Where I'm looking for a great debug type of Cheat Sheet/tutorial. -- http://mail.python.org/mailman/listinfo/python-list
Re: *args question
On Mar 26, 1:17 am, grocery_stocker wrote:
> On Mar 25, 7:05 am, grocery_stocker wrote:
>
>
>
> > Given the following code...
>
> > #!/usr/bin/env python
>
> > import time
> > import thread
>
> > def myfunction(string,sleeptime,*args):
> > while 1:
>
> > print string
> > time.sleep(sleeptime) #sleep for a specified amount of time.
>
> > if __name__=="__main__":
>
> > thread.start_new_thread(myfunction,("Thread No:1",2))
>
> > while 1:pass
>
> > Taken from following URLhttp://linuxgazette.net/107/pai.html
>
> > How can myfunction() extract the tuple ("Thread No:1",2) from
> > start_new_thread() if myfunction is only being passed the single arg
> > ("Thread No:1",2)
>
> The only thing that I think of is that the tuple ("Thread No:1",2) is
> somehow being extract before it gets passed to myfunction(). Ie,
> something like the following...
>
> [cdal...@localhost ~]$ python
> Python 2.4.3 (#1, Oct 1 2006, 18:00:19)
> [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> def
> myfunction(first, second, *args):
>
> ... print "The formal args are: ", args
> ... print "the first value is:", first
> ... print "the second value is:", second
> ...>>> a, b = (1,2)
> >>> myfunction(a,b)
>
> The formal args are: ()
> the first value is: 1
> the second value is: 2
Manual sez:
thread.start_new_thread(function, args[, kwargs])
where args must be a tuple
so thread.start_new_thread does this (ignoring the kwargs):
function(*args)
or it would if it were written in Python instead of C.
HTH
John
--
http://mail.python.org/mailman/listinfo/python-list
Re: Does __init__ of subclass need the same argument types as __init__ of base class?
Bruno Desthuilliers schrieb:
> Sibylle Koczian a écrit :
> (snip)
>>
>>
>> The print command inside the __init__ method isn't executed, so that
>> method doesn't seem to start at all.
>
> this often happens with (usually C-coded) immutable types. The
> initializer is not called, only the "proper" constructor (__new__). The
> following should work (not tested):
>
> class Meindatum(datetime.date):
>def __new__(self, datum):
> print "meindatum"
> return datetime.date(datum.year, datum.month, datum.day)
>
Thank you, that works, and I learned something (didn't know how Python
objects are created). After some trial, error and searching on the
Python website I found how to give Meindatum additional data attributes.
Now it looks like this:
class Sonderdatum(datetime.date):
"""
Date with additional attribute (integer)
"""
def __new__(cls, datum):
print "Hier Sonderdatum.__new__"
(x, y, z) = (datum.year, datum.month, datum.day)
print "Jahr: %d, Monat: %d, Tag: %d" % (x, y, z)
return super(Sonderdatum, cls).__new__(cls, datum.year,
datum.month,
datum.day)
def __init__(self, datum, sonder=0):
print "Hier Sonderdatum.__init__"
# superclass __init__ is _not_ called!
# super(Sonderdatum, self).__init__(x, y, z)
self.sonder = sonder
def testeSondertage():
datum = datetime.datetime.strptime("01.01.2009", "%x")
print repr(datum.date())
xx = Sonderdatum(datum.date())
print xx.year, xx.month, xx.day, xx.sonder
if __name__ == "__main__":
locale.setlocale(locale.LC_ALL, '')
testeSondertage()
And now I'll put this into something remotely useful.
Je vous prie d'agréer mes meilleurs salutations,
Sibylle
--
http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke wrote: > > i will go against the grain slightly and say that "len" is probably the > best compromise in most situations (although i admit i don't know what > count is) because i think it will work when you expect it to and break > when you have a bug in your program. > > using a simple boolean is more robust (and what i typically do in my own > code because i am often too lazy to think carefully), but if it is given > something that is not "list-like" you won't get an error until later in > your code (and typically the sooner an error is found, the better). > > but i may be wrong - are there any containers (apart from pathological > hand-crafted examples) that would not define __len__()? When writing my answer, I thought of generators, but I now find that those will have boolean value 'true' whether or not they have something to generate, so they will go wrong under either method. The same holds for iterators. So for now I can't find any good example. -- André Engels, [email protected] -- http://mail.python.org/mailman/listinfo/python-list
Re: *args question
grocery_stocker wrote:
On Mar 25, 7:05 am, grocery_stocker wrote:
Given the following code...
#!/usr/bin/env python
import time
import thread
def myfunction(string,sleeptime,*args):
while 1:
print string
time.sleep(sleeptime) #sleep for a specified amount of time.
if __name__=="__main__":
thread.start_new_thread(myfunction,("Thread No:1",2))
while 1:pass
Taken from following URLhttp://linuxgazette.net/107/pai.html
How can myfunction() extract the tuple ("Thread No:1",2) from
start_new_thread() if myfunction is only being passed the single arg
("Thread No:1",2)
The only thing that I think of is that the tuple ("Thread No:1",2) is
somehow being extract before it gets passed to myfunction(). Ie,
something like the following...
[cdal...@localhost ~]$ python
Python 2.4.3 (#1, Oct 1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
def myfunction(first, second, *args):
... print "The formal args are: ", args
... print "the first value is:", first
... print "the second value is:", second
...
a, b = (1,2)
myfunction(a,b)
The formal args are: ()
the first value is: 1
the second value is: 2
and if you call "myfunction(1,2,("Thread No:1",2))", you should
get something like
The formal args are: (('Thread No:1', 2),)
the first value is: 1
the second value is: 2
It's a list of the various items you put in:
def show_args(first, second, *args):
print "first", first
print "second", second
for i, arg in enumerate(args):
print "#%i %s" % (i, arg)
So you can either access "args[0]" (which is a bit dangerous, as
you assume there may be a value when there's not), or you can do
the more traditional thing of just treating it like a list as
above (e.g. iterating over it or using it in a list-comprehension).
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
On Mar 26, 2:21 am, "andrew cooke" wrote: > i will go against the grain slightly and say that "len" is probably the > best compromise in most situations (although i admit i don't know what > count is) because i think it will work when you expect it to and break > when you have a bug in your program. > > using a simple boolean is more robust (and what i typically do in my own > code because i am often too lazy to think carefully), but if it is given > something that is not "list-like" you won't get an error until later in > your code (and typically the sooner an error is found, the better). When you are doing something like if A and A[-1] == 'yadda': you won't have to wait long for the exception if A is not subscriptable :-) > but i may be wrong - are there any containers (apart from pathological > hand-crafted examples) that would not define __len__()? Very unlikely. -- http://mail.python.org/mailman/listinfo/python-list
SyntaxError: invalid syntax (windows)
I'm a total newbe to scripting not to mention python. However I was able to
successfully create a telnet script to initiate login, initiate tftp, exit,
exit, confirm and close session. Frustrated, possibly causing my own misery.
I replace the sript the script with the standard example.
import getpass
import sys
import telnetlib
HOST = "remote linux"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
Regardless of the script content, running in windows I constently get this
SyntaxError:
C:\Python30>python c:\Python30\scripts\telnet.py
File "c:\Python30\scripts\telnet.py", line 20
print tn.read_all()
^
SyntaxError: invalid syntax
C:\Python30>
The same script works fine from linux.
I have also notices some other slight differences: this is my original
script that runs and completes but only if I comment out print. Also tried
to run debug without success in windows again this worked fine in linux. To
run this script in linux I also had to remove the b syntax in the "b" in the
perentesis
import telnetlib
# import pdb
HOST = "HP switch"
tn = telnetlib.Telnet(HOST)
tn.read_until(b'Password: ')
tn.write(b'password\n')
pdb.set_trace()
tn.read_until(b'HP switch# ')
tn.write(b' sh time\n')
tn.read_until(b'HP switch# ')
tn.write(b'exit\n')
tn.read_until(b'HP switch> ')
tn.write(b'exit\n')
tn.read_until(b'Do you want to log out [y/n]? ')
tn.write(b'y')
print tn.read_all()
Any guidance would be appreciated.
Delrey
--
http://mail.python.org/mailman/listinfo/python-list
Re: *args question
On Mar 25, 8:28 am, Tim Chase wrote:
> grocery_stocker wrote:
> > On Mar 25, 7:05 am, grocery_stocker wrote:
> >> Given the following code...
>
> >> #!/usr/bin/env python
>
> >> import time
> >> import thread
>
> >> def myfunction(string,sleeptime,*args):
> >> while 1:
>
> >> print string
> >> time.sleep(sleeptime) #sleep for a specified amount of time.
>
> >> if __name__=="__main__":
>
> >> thread.start_new_thread(myfunction,("Thread No:1",2))
>
> >> while 1:pass
>
> >> Taken from following URLhttp://linuxgazette.net/107/pai.html
>
> >> How can myfunction() extract the tuple ("Thread No:1",2) from
> >> start_new_thread() if myfunction is only being passed the single arg
> >> ("Thread No:1",2)
>
> > The only thing that I think of is that the tuple ("Thread No:1",2) is
> > somehow being extract before it gets passed to myfunction(). Ie,
> > something like the following...
>
> > [cdal...@localhost ~]$ python
> > Python 2.4.3 (#1, Oct 1 2006, 18:00:19)
> > [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> def myfunction(first, second, *args):
> > ... print "The formal args are: ", args
> > ... print "the first value is:", first
> > ... print "the second value is:", second
> > ...
> a, b = (1,2)
> myfunction(a,b)
> > The formal args are: ()
> > the first value is: 1
> > the second value is: 2
>
> and if you call "myfunction(1,2,("Thread No:1",2))", you should
> get something like
>
>The formal args are: (('Thread No:1', 2),)
>the first value is: 1
>the second value is: 2
>
> It's a list of the various items you put in:
>
>def show_args(first, second, *args):
> print "first", first
> print "second", second
> for i, arg in enumerate(args):
>print "#%i %s" % (i, arg)
>
> So you can either access "args[0]" (which is a bit dangerous, as
> you assume there may be a value when there's not), or you can do
> the more traditional thing of just treating it like a list as
> above (e.g. iterating over it or using it in a list-comprehension).
>
Maybe I'm missing it, but in the original code, the line had
thread.start_new_thread(myfunction,("Thread No:1",2))
It has a single arg ("Thread No:1",2) versus something like
thread.start_new_thread(myfunction,1, 2, ("Thread No:1",2))
But
def myfunction(string,sleeptime,*args):
clearly takes two args. I don't get how the single arg ("Thread No:1",
2) in start_new_thread() gets magically converted two arges, string
and sleeptime, before it reaches myfunction().
--
http://mail.python.org/mailman/listinfo/python-list
Re: SyntaxError: invalid syntax (windows)
Python Newsgroup wrote:
I'm a total newbe to scripting not to mention python. However I was
able to successfully create a telnet script to initiate login,
initiate tftp, exit, exit, confirm and close session. Frustrated,
possibly causing my own misery. I replace the sript the script with
the standard example.
import getpass
import sys
import telnetlib
HOST = "remote linux"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
Regardless of the script content, running in windows I constently get
this SyntaxError:
C:\Python30>python c:\Python30\scripts\telnet.py
File "c:\Python30\scripts\telnet.py", line 20
print tn.read_all()
^
SyntaxError: invalid syntax
C:\Python30>
There's the clue:
In python 3.X, print is a function call
print(tn.read_all() )
with lots of formatting and line-ending features
In python 2.X, print is a statement:
print tn.read_all()
If you want one script to work for both Windows and Linux, then you
should probably
be running the same version of Python on each. At least both versions
should be on
the same side for the Python 2.x/3.x version change.
Gary Herron
The same script works fine from linux.
I have also notices some other slight differences: this is my original
script that runs and completes but only if I comment out print. Also
tried to run debug without success in windows again this worked fine
in linux. To run this script in linux I also had to remove the b
syntax in the "b" in the perentesis
import telnetlib
# import pdb
HOST = "HP switch"
tn = telnetlib.Telnet(HOST)
tn.read_until(b'Password: ')
tn.write(b'password\n')
pdb.set_trace()
tn.read_until(b'HP switch# ')
tn.write(b' sh time\n')
tn.read_until(b'HP switch# ')
tn.write(b'exit\n')
tn.read_until(b'HP switch> ')
tn.write(b'exit\n')
tn.read_until(b'Do you want to log out [y/n]? ')
tn.write(b'y')
print tn.read_all()
Any guidance would be appreciated.
Delrey
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list
Re: Debugging in Py
I'm just wondering if you all have any resources on Debugging that you all would "recommend." Due to the fact I'm doing some debugging as a beginner and this has the best of me, and I'm looking at trying to learn more about what and how to debug within Py using print, and etc... For most of what I do, simply dropping a "print" line suffices. For more complex stuff where I want to do a bit of on-the-fly inspection, I'll often just add the line import pdb; pdb.set_trace() to my code and it will halt at a debugger prompt. You can then use the batteries-included "pdb" debugger to inspect your program's internal state. You can read up on it at http://docs.python.org/library/pdb.html#id1 http://www.oreillynet.com/pub/a/python/2005/09/01/debugger.html http://www.ferg.org/papers/debugging_in_python.html I use it mostly to dump variable contents and step into/over lines of code (there are much deeper abilities that I hardly scratch). -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: SyntaxError: invalid syntax (windows)
Python Newsgroup wrote:
I'm a total newbe to scripting not to mention python. However I was able
to successfully create a telnet script to initiate login, initiate tftp,
exit, exit, confirm and close session. Frustrated, possibly causing my
own misery. I replace the sript the script with the standard example.
import getpass
import sys
import telnetlib
HOST = "remote linux"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ls\n")
tn.write("exit\n")
print tn.read_all()
Regardless of the script content, running in windows I constently get
this SyntaxError:
C:\Python30>python c:\Python30\scripts\telnet.py
File "c:\Python30\scripts\telnet.py", line 20
print tn.read_all()
^
SyntaxError: invalid syntax
C:\Python30>
The same script works fine from linux.
I have also notices some other slight differences: this is my original
script that runs and completes but only if I comment out print. Also
tried to run debug without success in windows again this worked fine in
linux. To run this script in linux I also had to remove the b syntax in
the "b" in the perentesis
import telnetlib
# import pdb
HOST = "HP switch"
tn = telnetlib.Telnet(HOST)
tn.read_until(b'Password: ')
tn.write(b'password\n')
pdb.set_trace()
tn.read_until(b'HP switch# ')
tn.write(b' sh time\n')
tn.read_until(b'HP switch# ')
tn.write(b'exit\n')
tn.read_until(b'HP switch> ')
tn.write(b'exit\n')
tn.read_until(b'Do you want to log out [y/n]? ')
tn.write(b'y')
print tn.read_all()
Any guidance would be appreciated.
It looks like you're using Python 3.0 on Windows and Python 2.x on
Linux.
In Python 2.x, 'print' is a statement:
print tn.read_all()
In Python 3.x, 'print' is a function, so you need to write:
print(tn.read_all())
--
http://mail.python.org/mailman/listinfo/python-list
Re: Problems with threaded Hotkey application
Anita Whitney wrote: > A window comes up saying "hotkeyapp has stopped working." How do I > get in there to "move the RegisterHotKey line to within the thread's > run method," etc.? Im trying to do this myself and not pay Acer tech > support. Thanks, Anita Whitney Is this a wxPython application that you are writing[1]? Can you post the python code that you are trying to modify? I'm not sure what Acer's tech support has to do with all this. [1] http://wiki.wxpython.org/RegisterHotKey -- for those that haven't ever seen RegisterHotKey before. -- http://mail.python.org/mailman/listinfo/python-list
Re: *args question
Maybe I'm missing it, but in the original code, the line had
thread.start_new_thread(myfunction,("Thread No:1",2))
It has a single arg ("Thread No:1",2) versus something like
thread.start_new_thread(myfunction,1, 2, ("Thread No:1",2))
But
def myfunction(string,sleeptime,*args):
clearly takes two args. I don't get how the single arg ("Thread No:1",
2) in start_new_thread() gets magically converted two arges, string
and sleeptime, before it reaches myfunction().
As John pointed out, the start_new_thread passes *args to your
function. So you would define a your function:
def myfunc(some_string, some_int):
print "The string value:", some_string
print "The int value", some_int
thread.start_new_thread(myfunc, "some string", 42)
should print
The string value: some string
The int value: 42
because all the subsequent values after the function-handle/name
get passed into the function when it gets called. As if the
start_new_thread() function was defined as
def start_new_thread(fn, *args, **kwargs):
thread_magic_happens_here()
result = fn(*args, **kwargs)
return more_thread_magic_happens_here(result)
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: Another form of dynamic import
On 25 Mrz., 15:23, Marco Nawijn wrote: > Hello, > > In short I would like to know if somebody knows if it is possible to > re-execute a statement that raised an exception? I will explain the > reason by providing a small introduction on why this might be nice in > my case > and some example code. > > I am using the python bindings to a *very* large C++ library. About > 5000 classes divided over approx. 450 different > packages are exposed through the Python interface. To reduce the > number of import statements that need to be inserted and to limit the > number of wildcard imports it would be very helpful if class names > could be automatically imported from the proper module. There is no > problem in finding out the proper module given a (valid) class name. > > As an example, look at the following statement > > >> aPoint = gp_Pnt(1.0, 0.0, 0.0) # Oops, this will raise a NameError, > >> since > > # gp_Pnt class > is unknown > > NameError: name 'gp_Pnt' is not defined > > As indicated, this will raise a NameError exception. What I would like > to do is something like the following (pseudo-code): > > try: > > > aPoint = gp_Pnt(1.0, 0.0, 0.0)[1] > > > > except NameError, e: > > name = e.args[0].split[1] > > if isValid(name): > doImport(name) > ===> Can I go back to statement [1] from this point? > else: > raise e > > There is no problem in catching the exception, finding out which name > is unknown to python and check if this is a valid name for my library. > My question is, is there any possibility of going back to the > statement that raised the error, re-execute the statement and > continue? > > Thanks for any thoughts and suggestions. > > Marco There is no call/cc continuation in Python when you are asking for such a thing. I wonder however why you don't try lazy attribute access? Instead of making a raw function call like that to gp_Pnt, one can thread all calls to the C++ system through an object that implements __getattr__ and loads new names incrementally if one is missing. -- http://mail.python.org/mailman/listinfo/python-list
Re: SyntaxError: invalid syntax (windows)
Thats newbe experience for ya ;-) thanks. Its seems to work and leads to another question. whether running the script or stepping thru the process at the command line I get what looks like hex C:\Python30>python \Python30\scripts\telnet-tftp1.py b'\x1b[24;1H\x1b[24;31H\x1b[24;1H\x1b[?25h\x1b[24;31H\x1b[24;31Hy\x1b[24;31H\x1b [?25h\x1b[24;32H\x1b[24;0H\x1bE\x1b[24;1H\x1b[24;32H\x1b[24;1H\x1b[2K\x1b[24;1H\ x1b[?25h\x1b[24;1H\x1b[1;24r\x1b[24;1H\x1b[2J\x1b[?7l\x1b[1;24r\x1b[?6l\x1b[24;1 H\x1b[?25h\x1b[24;1H\x1b[?6l\x1b[1;0r\x1b[?7l\x1b[2J\x1b[24;1H\x1b[1;1H\x1b[2K\x 1b[24;1H\n\r' C:\Python30> I can verify the script ran thru and executed the telnet commands. is there a switch to convert to binary/ASCI or reduce the logging of the telnet session ??? Thanks again Chris "Gary Herron" wrote in message news:[email protected]... Python Newsgroup wrote: I'm a total newbe to scripting not to mention python. However I was able to successfully create a telnet script to initiate login, initiate tftp, exit, exit, confirm and close session. Frustrated, possibly causing my own misery. I replace the sript the script with the standard example. import getpass import sys import telnetlib HOST = "remote linux" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() Regardless of the script content, running in windows I constently get this SyntaxError: C:\Python30>python c:\Python30\scripts\telnet.py File "c:\Python30\scripts\telnet.py", line 20 print tn.read_all() ^ SyntaxError: invalid syntax C:\Python30> There's the clue: In python 3.X, print is a function call print(tn.read_all() ) with lots of formatting and line-ending features In python 2.X, print is a statement: print tn.read_all() If you want one script to work for both Windows and Linux, then you should probably be running the same version of Python on each. At least both versions should be on the same side for the Python 2.x/3.x version change. Gary Herron The same script works fine from linux. I have also notices some other slight differences: this is my original script that runs and completes but only if I comment out print. Also tried to run debug without success in windows again this worked fine in linux. To run this script in linux I also had to remove the b syntax in the "b" in the perentesis import telnetlib # import pdb HOST = "HP switch" tn = telnetlib.Telnet(HOST) tn.read_until(b'Password: ') tn.write(b'password\n') pdb.set_trace() tn.read_until(b'HP switch# ') tn.write(b' sh time\n') tn.read_until(b'HP switch# ') tn.write(b'exit\n') tn.read_until(b'HP switch> ') tn.write(b'exit\n') tn.read_until(b'Do you want to log out [y/n]? ') tn.write(b'y') print tn.read_all() Any guidance would be appreciated. Delrey -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: *args question (correction)
thread.start_new_thread(myfunc, "some string", 42)
This should have been
thread.start_new_thread(myfunc, ("some string", 42))
because all the subsequent values after the function-handle/name
get passed into the function when it gets called. As if the
start_new_thread() function was defined as
def start_new_thread(fn, *args, **kwargs):
thread_magic_happens_here()
result = fn(*args, **kwargs)
return more_thread_magic_happens_here(result)
and this should have been
def start_new_thread(fn, args=[], kwargs={}):
thread_magic()
result = fn(*args, **kwargs)
My threading-library usage is a little rusty, so I forgot those
were literal parameters, not args/kwargs that became more
idiomatic in other code authored later.
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: distutils compiler flags for extension modules
Thanks! I'll try that. Sorry for replying so late - just didn't get to it. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: *args question
Try the following, to call your function yourself in this way:
def myfunction(string,sleeptime,*args):
while 1:
print "string is ", string
time.sleep(sleeptime) #sleep for a specified amount of time.
f = myfunction
r = ("Thread No:1",2)
f(*r)
The key here is the *r syntax, which is used in a function call to
turn a tuple (or list) into a separate set of arguments. It's kind of
the inverse of the *args you're already using.
DaveA
grocery_stocker wrote:
On Mar 25, 8:28 am, Tim Chase wrote:
grocery_stocker wrote:
< portions deleted ..>
Maybe I'm missing it, but in the original code, the line had
thread.start_new_thread(myfunction,("Thread No:1",2))
It has a single arg ("Thread No:1",2) versus something like
thread.start_new_thread(myfunction,1, 2, ("Thread No:1",2))
But
def myfunction(string,sleeptime,*args):
clearly takes two args. I don't get how the single arg ("Thread No:1",
2) in start_new_thread() gets magically converted two arges, string
and sleeptime, before it reaches myfunction().
--
http://mail.python.org/mailman/listinfo/python-list
Re: SyntaxError: invalid syntax (windows)
Gotcha, I got started from the telnet example listed in the docs. The linux install was via yum and installed 2.x instead. That explains it. Althought print (tn.read_all () ) runs in 2.x on linux. I have another problem maybe you cna help me with. My telnet output jibberish in windows: I cna parse some of the output for results but is there anyway to get rid of the jibberish. (looks like hex but I'm not sure) I can only use this tn.read_until(b'whatever string') Is this whats causing the output? the b switch. seems like I don't need it in linux. is that binary? Thanks C:\Python30>python \Python30\scripts\telnet-tftp1.py b'\x1b[24;1H\x1b[24;31H\x1b[24;1H\x1b[?25h\x1b[24;31H\x1b[24;31Hy\x1b[24;31H\x1b [?25h\x1b[24;32H\x1b[24;0H\x1bE\x1b[24;1H\x1b[24;32H\x1b[24;1H\x1b[2K\x1b[24;1H\ x1b[?25h\x1b[24;1H\x1b[1;24r\x1b[24;1H\x1b[2J\x1b[?7l\x1b[1;24r\x1b[?6l\x1b[24;1 H\x1b[?25h\x1b[24;1H\x1b[?6l\x1b[1;0r\x1b[?7l\x1b[2J\x1b[24;1H\x1b[1;1H\x1b[2K\x 1b[24;1H\n\r' C:\Python30> "MRAB" wrote in message news:[email protected]... Python Newsgroup wrote: I'm a total newbe to scripting not to mention python. However I was able to successfully create a telnet script to initiate login, initiate tftp, exit, exit, confirm and close session. Frustrated, possibly causing my own misery. I replace the sript the script with the standard example. import getpass import sys import telnetlib HOST = "remote linux" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() Regardless of the script content, running in windows I constently get this SyntaxError: C:\Python30>python c:\Python30\scripts\telnet.py File "c:\Python30\scripts\telnet.py", line 20 print tn.read_all() ^ SyntaxError: invalid syntax C:\Python30> The same script works fine from linux. I have also notices some other slight differences: this is my original script that runs and completes but only if I comment out print. Also tried to run debug without success in windows again this worked fine in linux. To run this script in linux I also had to remove the b syntax in the "b" in the perentesis import telnetlib # import pdb HOST = "HP switch" tn = telnetlib.Telnet(HOST) tn.read_until(b'Password: ') tn.write(b'password\n') pdb.set_trace() tn.read_until(b'HP switch# ') tn.write(b' sh time\n') tn.read_until(b'HP switch# ') tn.write(b'exit\n') tn.read_until(b'HP switch> ') tn.write(b'exit\n') tn.read_until(b'Do you want to log out [y/n]? ') tn.write(b'y') print tn.read_all() Any guidance would be appreciated. It looks like you're using Python 3.0 on Windows and Python 2.x on Linux. In Python 2.x, 'print' is a statement: print tn.read_all() In Python 3.x, 'print' is a function, so you need to write: print(tn.read_all()) -- http://mail.python.org/mailman/listinfo/python-list
Re: SyntaxError: invalid syntax (windows)
Python Newsgroup wrote: Gotcha, I got started from the telnet example listed in the docs. The linux install was via yum and installed 2.x instead. That explains it. Althought print (tn.read_all () ) runs in 2.x on linux. I have another problem maybe you cna help me with. My telnet output jibberish in windows: I cna parse some of the output for results but is there anyway to get rid of the jibberish. (looks like hex but I'm not sure) I can only use this tn.read_until(b'whatever string') Is this whats causing the output? the b switch. seems like I don't need it in linux. is that binary? Thanks C:\Python30>python \Python30\scripts\telnet-tftp1.py b'\x1b[24;1H\x1b[24;31H\x1b[24;1H\x1b[?25h\x1b[24;31H\x1b[24;31Hy\x1b[24;31H\x1b [?25h\x1b[24;32H\x1b[24;0H\x1bE\x1b[24;1H\x1b[24;32H\x1b[24;1H\x1b[2K\x1b[24;1H\ x1b[?25h\x1b[24;1H\x1b[1;24r\x1b[24;1H\x1b[2J\x1b[?7l\x1b[1;24r\x1b[?6l\x1b[24;1 H\x1b[?25h\x1b[24;1H\x1b[?6l\x1b[1;0r\x1b[?7l\x1b[2J\x1b[24;1H\x1b[1;1H\x1b[2K\x 1b[24;1H\n\r' C:\Python30> They look like control sequences for a terminal. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another form of dynamic import
On Mar 25, 10:23 am, Marco Nawijn wrote: > Hello, > > In short I would like to know if somebody knows if it is possible to > re-execute a statement that raised an exception? I will explain the > reason by providing a small introduction on why this might be nice in > my case > and some example code. > > I am using the python bindings to a *very* large C++ library. About > 5000 classes divided over approx. 450 different > packages are exposed through the Python interface. To reduce the > number of import statements that need to be inserted and to limit the > number of wildcard imports it would be very helpful if class names > could be automatically imported from the proper module. There is no > problem in finding out the proper module given a (valid) class name. > > As an example, look at the following statement > > >> aPoint = gp_Pnt(1.0, 0.0, 0.0) # Oops, this will raise a NameError, > >> since > > # gp_Pnt class > is unknown > > NameError: name 'gp_Pnt' is not defined > > As indicated, this will raise a NameError exception. What I would like > to do is something like the following (pseudo-code): > > try: > > > aPoint = gp_Pnt(1.0, 0.0, 0.0) [1] > > > > except NameError, e: > > name = e.args[0].split[1] > > if isValid(name): > doImport(name) > ===> Can I go back to statement [1] from this point? > else: > raise e > > There is no problem in catching the exception, finding out which name > is unknown to python and check if this is a valid name for my library. > My question is, is there any possibility of going back to the > statement that raised the error, re-execute the statement and > continue? > > Thanks for any thoughts and suggestions. > > Marco You can always use a loop: recover=True while True: try: aPoint = gp_Pnt(1.0, 0.0, 0.0)[1] except NameError, e: if recover: recover=False name = e.args[0].split[1] if isValid(name): doImport(name) else: raise e else: break -- http://mail.python.org/mailman/listinfo/python-list
Re: SyntaxError: invalid syntax (windows)
MRAB wrote: Python Newsgroup wrote: Gotcha, I got started from the telnet example listed in the docs. The linux install was via yum and installed 2.x instead. That explains it. Althought print (tn.read_all () ) runs in 2.x on linux. I have another problem maybe you cna help me with. My telnet output jibberish in windows: I cna parse some of the output for results but is there anyway to get rid of the jibberish. (looks like hex but I'm not sure) I can only use this tn.read_until(b'whatever string') Is this whats causing the output? the b switch. seems like I don't need it in linux. is that binary? Thanks C:\Python30>python \Python30\scripts\telnet-tftp1.py b'\x1b[24;1H\x1b[24;31H\x1b[24;1H\x1b[?25h\x1b[24;31H\x1b[24;31Hy\x1b[24;31H\x1b [?25h\x1b[24;32H\x1b[24;0H\x1bE\x1b[24;1H\x1b[24;32H\x1b[24;1H\x1b[2K\x1b[24;1H\ x1b[?25h\x1b[24;1H\x1b[1;24r\x1b[24;1H\x1b[2J\x1b[?7l\x1b[1;24r\x1b[?6l\x1b[24;1 H\x1b[?25h\x1b[24;1H\x1b[?6l\x1b[1;0r\x1b[?7l\x1b[2J\x1b[24;1H\x1b[1;1H\x1b[2K\x 1b[24;1H\n\r' C:\Python30> They look like control sequences for a terminal. Indeed. \x1b == \033 == 27 == ESCAPE. 'ESC [' is the standard prefix for ANSI terminal control sequences. http://en.wikipedia.org/wiki/ANSI_escape_code "32-bit character-mode (subsystem:console) Windows applications don't write ANSI escape sequences to the console. They must interpret the escape code actions and call the native Console API instead to accomplish the proper result. If you do write the sequences directly, all you'll get is the text of the sequence on the screen, not the action intended." I mostly see a crazy mixture of ESC [ row , col H cursor position commands. For you app, parse out and ignore the codes not skipped by .read_until calls. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Another form of dynamic import
Marco Nawijn wrote: In short I would like to know if somebody knows if it is possible to re-execute a statement that raised an exception? In short, no. As an example, look at the following statement aPoint = gp_Pnt(1.0, 0.0, 0.0) # Oops, this will raise a NameError, since # gp_Pnt class is unknown NameError: name 'gp_Pnt' is not defined Either make sure names are defined before you use them (easy) or provide alternative code in the except clause. If you actually have the name written literally in the code, you should simply import it first, so I presume you have a more complicated use case where the name to use is dynamically defined in a string. If so, do something like aPoint = MyImporter(class_name)(1.0, 0.0, 0.0) where MyImporter.__new__ imports and returns the class Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
iteration without storing a variable
So The metasploit framework was suffering from some performance issues
which they fixed. http://www.metasploit.com/blog/
I was interested in comparing this to python. Language comparisons are
not generally very useful for a number of reasons, but some might find
this interesting.
Clearly the python operator += is way faster than ruby's:
$ time python -c 'a = "A";
for r in xrange(10): a += "A" '
real0m0.109s
user0m0.100s
sys 0m0.010s
$ time ruby -e 'a = "A"; 10.times { a += "A" }'
real0m3.113s
user0m3.110s
sys 0m0.010s
one more zero and the difference is magnified even more:
$ time python -c 'a = "A";
for r in xrange(100): a += "A" '
real0m1.208s
user0m0.940s
sys 0m0.270s
$ time ruby -e 'a = "A"; 100.times { a += "A" }'
^C
I wasn't patient enough to wait more than 30 seconds for ruby
to finish.
If you use a python list instead of a string (and join at the end) you
get even better performance:
$ time python -c 'a = ["A"];
for r in xrange(100): a.append("A")
"".join(a)'
real0m0.889s
user0m0.870s
sys 0m0.020s
This seems to compare closely to the improved ruby code:
$ time ruby -e 'a = "A"; 100.times { a << "A" }'
real0m0.920s
user0m0.920s
sys 0m0.000s
Interestingly enough this is even with the slight performance hit for
initializing python vs. initializing ruby:
$ time ruby -e ''
real0m0.008s
user0m0.010s
sys 0m0.000s
$ time python -c ''
real0m0.023s
user0m0.010s
sys 0m0.020s
Obviously speed isn't everything and I choose python because it's more
clean and readable, but it is interesting. The main question this raises
for me is, "is it possible to more closely replicate the ruby code and
do a loop without variable assignment?"
Of course that was quickly followed by, "does the variable assignment
on each iteration really cause any kind of performance hit?" In
reference to the difference between ruby and python, it seems the
answer is no. I'm guessing that this is because the iteration number
needs to be stored anyway during a loop, so making it availble has
essentially zero cost (sound right?).
$ time python -c 'for r in xrange(100): pass'
real0m0.210s
user0m0.210s
sys 0m0.000s
$ time ruby -e '100.times { }'
real0m0.259s
user0m0.250s
sys 0m0.000s
Anyone see anything I missed? Any additional info? Anyone get different
results?
--
Josh Dukes
MicroVu IT Department
--
http://mail.python.org/mailman/listinfo/python-list
Re: Another form of dynamic import
Also, instead of caching exceptions you can do lazy lookups kinda like this: - # a.py class A: pass - # b.py class B: pass - # c.py class D: pass class E: pass - # iface.py class LazyInterface(object): _attr_dict = dict(A='a', B='b', C='c', D='c') _attr_cache = dict() _mod_cache = dict() def __getattr__(self, name): if name in self._attr_cache: return self._attr_cache[name] elif name in self._attr_dict: module_name = self._attr_dict[name] self._mod_cache[module_name] = self._mod_cache.get(module_name,__import__(module_name)) self._attr_cache[name] = getattr(self._mod_cache[module_name], name) return self._attr_cache[name] else: raise AttributeError >>> from iface import LazyInterface >>> i = LazyInterface() >>> a = i.A() >>> a >>> c = i.C() >>> c >>> d = i.D() >>> d There is probably a cleaner/more robust way of doing the above, but you get the idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: iteration without storing a variable
Josh Dukes wrote: > $ time python -c 'a = "A"; > for r in xrange(10): a += "A" ' > > real 0m0.109s > user 0m0.100s > sys 0m0.010s > > Anyone get different results? Sure: $ time python -c 'a = "A"; for r in xrange(10): a += "A" ' real0m0.140s user0m0.132s sys 0m0.008s Stefan (BTW, this is using Python 2.5.2 on Ubuntu Linux etc.pp., but no-one's interested in these details anyway, right?) -- http://mail.python.org/mailman/listinfo/python-list
time.strptime() undocumented difference python 2.5.1>2.5.2
A server that runs one of my programs was upgraded to Debian Lenny
last night, which moved it from Python 2.4.4 to 2.5.2. This caused
immediate trouble. At one point, data is parsed from a Web page, and
among other things a time date group is collected. This is in a nice
human readable format, but I want it in RFC 822 format because it's
going to be used in an outbound GeoRSS feed and it's a requirement.
So the time group is split up with a regex, merged into one string,
and fed to time.strptime() with a fitting format, then passed to
Utils.formatdate() and used. The time group looks like this:
25/03/2009 21:05:00
Code:
if airline not in whitelist:
retime = re.split('[-\s:/]', rawtime)
timeinput = ''.join(retime)
t = time.strptime(timeinput, "%d %m %Y %H %M %S")
timeout = Utils.formatdate(t)
Error:
Traceback (most recent call
last):
File "/home/yorksranter/vfeed-data/bothv7.py", line 46, in
t = time.strptime(timeinput, "%d %m %Y %H %M
%S")
File "/usr/lib/python2.5/_strptime.py", line 330, in
strptime
(data_string,
format))
ValueError: time data did not match format: data=25032009210500 fmt=
%d %m %Y %H %M %S
Weirdness:
Python 2.5.2 (r252:60911, Jan 4 2009, 21:59:32) #the
server
[GCC 4.3.2] on
linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> timeinput = '25032009210500'
>>> import time
>>> t = time.strptime(timeinput, "%d %m %Y %H %M %S")
Traceback (most recent call
last):
File "", line 1, in
File "/usr/lib/python2.5/_strptime.py", line 330, in
strptime
(data_string,
format))
ValueError: time data did not match format: data=25032009210500 fmt=
%d %m %Y %H %M %S
But
Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57) #the laptop
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> timeinput = '25032009210500'
>>> t = time.strptime(timeinput, "%d %m %Y %H %M %S")
>>> print t
(2009, 3, 25, 21, 5, 0, 2, 84, -1)
Docs (http://docs.python.org/library/time.html#time.strptime) say:
Parses a string representing a time according to a format. If I send
it through str() to make absolutely sure it is a string I get the same
error.
I note from the changelog that there was a change affecting
time.strptime()...(http://www.python.org/download/releases/2.5.2/
NEWS.txt)
- Bug #1730389: Have time.strptime() match spaces in a format argument
with
``\s+`` instead of ``\s*``.
- Bug #1290505: Properly clear time.strptime's locale cache when the
locale
changes between calls. Backport of r54646 and r54647.
I don't see that either of these should break it, but it's got to be a
suspect.
--
http://mail.python.org/mailman/listinfo/python-list
Re: iteration without storing a variable
well if we're interested in that... $ uname -a Linux IT2-JD 2.6.27-gentoo-r8 #1 SMP Tue Mar 17 14:28:19 PDT 2009 x86_64 Intel(R) Pentium(R) D CPU 2.80GHz GenuineIntel GNU/Linux $ python --version Python 2.5.2 $ ruby --version ruby 1.8.6 (2008-08-11 patchlevel 287) [x86_64-linux] but I was more talking about the speed differences between ruby and python. On Wed, 25 Mar 2009 20:13:13 +0100 Stefan Behnel wrote: > Josh Dukes wrote: > > $ time python -c 'a = "A"; > > for r in xrange(10): a += "A" ' > > > > real0m0.109s > > user0m0.100s > > sys 0m0.010s > > > > Anyone get different results? > > Sure: > > $ time python -c 'a = "A"; > for r in xrange(10): a += "A" ' > > real0m0.140s > user0m0.132s > sys 0m0.008s > > > Stefan > > > (BTW, this is using Python 2.5.2 on Ubuntu Linux etc.pp., but no-one's > interested in these details anyway, right?) > -- > http://mail.python.org/mailman/listinfo/python-list -- Josh Dukes MicroVu IT Department -- http://mail.python.org/mailman/listinfo/python-list
Re: Another form of dynamic import
On 2009-03-25, Marco Nawijn wrote: > Hello, > > In short I would like to know if somebody knows if it is possible to > re-execute a statement that raised an exception? I will explain the > reason by providing a small introduction on why this might be nice in > my case > and some example code. > > I am using the python bindings to a *very* large C++ library. About > 5000 classes divided over approx. 450 different > packages are exposed through the Python interface. To reduce the > number of import statements that need to be inserted and to limit the > number of wildcard imports it would be very helpful if class names > could be automatically imported from the proper module. There is no > problem in finding out the proper module given a (valid) class name. Maybe this helps: http://www.connellybarnes.com/code/autoimp/ Regards, Anton -- http://mail.python.org/mailman/listinfo/python-list
Re: time.strptime() undocumented difference python 2.5.1>2.5.2
TYR wrote:
A server that runs one of my programs was upgraded to Debian Lenny
last night, which moved it from Python 2.4.4 to 2.5.2. This caused
immediate trouble. At one point, data is parsed from a Web page, and
among other things a time date group is collected. This is in a nice
human readable format, but I want it in RFC 822 format because it's
going to be used in an outbound GeoRSS feed and it's a requirement.
So the time group is split up with a regex, merged into one string,
and fed to time.strptime() with a fitting format, then passed to
Utils.formatdate() and used. The time group looks like this:
25/03/2009 21:05:00
Code:
if airline not in whitelist:
retime = re.split('[-\s:/]', rawtime)
timeinput = ''.join(retime)
t = time.strptime(timeinput, "%d %m %Y %H %M %S")
timeout = Utils.formatdate(t)
Error:
Traceback (most recent call
last):
File "/home/yorksranter/vfeed-data/bothv7.py", line 46, in
t = time.strptime(timeinput, "%d %m %Y %H %M
%S")
File "/usr/lib/python2.5/_strptime.py", line 330, in
strptime
(data_string,
format))
ValueError: time data did not match format: data=25032009210500 fmt=
%d %m %Y %H %M %S
Weirdness:
Python 2.5.2 (r252:60911, Jan 4 2009, 21:59:32) #the
server
[GCC 4.3.2] on
linux2
Type "help", "copyright", "credits" or "license" for more
information.
timeinput = '25032009210500'
import time
t = time.strptime(timeinput, "%d %m %Y %H %M %S")
Traceback (most recent call
last):
File "", line 1, in
File "/usr/lib/python2.5/_strptime.py", line 330, in
strptime
(data_string,
format))
ValueError: time data did not match format: data=25032009210500 fmt=
%d %m %Y %H %M %S
But
Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57) #the laptop
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import time
timeinput = '25032009210500'
t = time.strptime(timeinput, "%d %m %Y %H %M %S")
print t
(2009, 3, 25, 21, 5, 0, 2, 84, -1)
Docs (http://docs.python.org/library/time.html#time.strptime) say:
Parses a string representing a time according to a format. If I send
it through str() to make absolutely sure it is a string I get the same
error.
I note from the changelog that there was a change affecting
time.strptime()...(http://www.python.org/download/releases/2.5.2/
NEWS.txt)
- Bug #1730389: Have time.strptime() match spaces in a format argument
with
``\s+`` instead of ``\s*``.
- Bug #1290505: Properly clear time.strptime's locale cache when the
locale
changes between calls. Backport of r54646 and r54647.
I don't see that either of these should break it, but it's got to be a
suspect.
I think it's due to bug #1730389. This says that a space in the format
string should match _at least one_ space in the string it's parsing.
Your format is "%d %m %Y %H %M %S" (it contains spaces) but your string
is "25032009210500" (it doesn't contain spaces), hence the failure.
I suggest you change:
timeinput = ''.join(retime)
to:
timeinput = ' '.join(retime)
It'll make the string a little clearer anyway: "25 03 2009 21 05 00".
--
http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
On Mar 25, 7:38 am, srinivasan srinivas wrote: > For ex: to check list 'A' is empty or not.. > if A == []: > if A.count == 0: > if len(A) == 0: > if not A: PEP 8 recommends the latter. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: iteration without storing a variable
Josh Dukes wrote: > $ python --version > Python 2.5.2 > > $ ruby --version > ruby 1.8.6 (2008-08-11 patchlevel 287) [x86_64-linux] > > but I was more talking about the speed differences between ruby and python. I heard that Ruby 1.9 is supposed to be a lot faster than 1.8 in many aspects (as is Py2.6 compared to 2.5 or 2.4, BTW), so I think version numbers matter a lot in this case. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
Andre Engels wrote: > On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke wrote: >> i will go against the grain slightly and say that "len" is probably the >> best compromise in most situations (although i admit i don't know what [...] >> but i may be wrong - are there any containers (apart from pathological >> hand-crafted examples) that would not define __len__()? > When writing my answer, I thought of generators, but I now find that > those will have boolean value 'true' whether or not they have > something to generate, so they will go wrong under either method. The > same holds for iterators. So for now I can't find any good example. actually, the implication of what you said is probably worth emphasising to the original poster: often you don't need to test whether a list is empty or not, you simply iterate over its contents: for x in foo: # do something this will then work with lists, tuples, sets, but also with iterators and generators (which would give incorrect results in a test). in all cases, "do something" will not happen if there are no data to process. andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Mangle function name with decorator?
On Wed, 2009-03-18 at 08:18 -0700, Adam wrote:
> On Mar 18, 10:33 am, "J. Cliff Dyer" wrote:
> > You might be interested in redefining __getattribute__(self, attr) on
> > your class. This could operate in conjunction with the hash tables
> > (dictionaries) mentioned by andrew cooke. i.e. (untested code):
> >
> > class C(object):
> > def __init__(self):
> > self._get_table = {}
> > self._post_table = {}
> >
> > def __getattribute__(self, x):
> > if self.method=='GET':
> > return object.__getattribute__(self, _get_table)[x]
> > elif self.method=='POST':
> > return object.__getattribute__(self, _post_table)[x]
> > else:
> > raise AttributeError
> > @GET
> > def foo(x):
> > return "Got", x
> > @POST
> > def foo(x)
> > return "Posted to", x
> >
> > This is definitely not functional code, but might get you in the right
> > direction on __getattribute__. __getattr__ might also work for you. I
> > haven't worked too much with these corners of python.
> >
> > Cheers,
> > Cliff
>
> Hey, Cliff. Thanks for sharing this idea. Unfortunately, providing a
> way to actually call the method with the mangled name is relatively
> easy, and there are options there. The real issue, to me, seems to be
> finding a way to prevent Python from eating all but the last version
> of a function definition in a class. While decorators are a elegant
> and unintrusive approach, I don't believe that there is any way for a
> decorator to collection information in a data structure and then
> provide that data back to the class instance or the class's metaclass.
>
If your __getattribute__ dispatches method calls from a dictionary, it
shouldn't matter if the original name of the method has been blown away.
The actual method object lives on, and is accessed normally from the
user's standpoint.
I'm just thinking out loud now on ideas I haven't tested myself, but
what if your decorator were itself a method of the same class, so you
had something like this:
class BarBar(object):
def decorate_get(self, func):
pass
def decorate_post(self, func):
pass
@self.decorate_get
def foo(self):
pass
@self.decorate_post
def foo(self):
pass
Then the decorator has access to self, and can pass around whatever
information it needs. Maybe the decoration methods should live on a
base class somewhere.
class Decoratable(object):
def get(self, func):
pass
def post(self, func):
pass
class BarBar(Decoratable):
@self.get
def foo(self):
pass
@self.post
def foo(self)
pass
> I'm beginning to think that I am trying to get the square peg of
> Python to fit into the round hole of a .NET idiom.
Well, square is just one abstraction layer away from round anyway,
right?
> I am trying to
> borrow what I think is a really elegant and useful idiom from ASP.NET
> MVC. Specifically, in an ASP.NET MVC Controller class, I can have two
> methods with the same name that are called for different HTTP Verbs by
> applying an Attribute:
>
> public ActionResult Payment() {
> ViewData["Title"] = "Payment Information";
> ViewData["submit_text"] = "Next >";
>
> return View();
> }
>
> [AcceptVerbs(HttpVerbs.Post)]
> public ActionResult Payment(FormCollection form) {
>
> return RedirectToAction("Legal");
> }
>
> Right? The first Payment method is called when the Payment page is
> rendered. The second is called when the form that it contains is
> submitted. I find it to be readable, elegant and it does not intrude
> into the actual logic of the method itself. The alternatives that I
> can readily identify are less-than-optimal. For instance, if could
> just have an if statement inside the body of the method that branches
> on the HTTP verb:
>
> def Payment(self):
> if self.request.verb == 'GET':
> # Do stuff for GET
> elif self.request.verb == 'POST':
> # So stuff for POST
>
> Yes, it would work, but it is ugly and requires me to mix in the same
> function the behaviors for two very separate things.
>
> Or, I could do something like this:
>
> def GET_Payment(self):
> # Do stuff for GET
>
> def POST_Payment(self):
> # Do stuff for POST
>
> This is trivially-easy to implement (in this case, a metaclass can
> very easily manipulate the namespace), but it makes the source code
> less appealing and just feels crufty and hacky. It also makes it
> difficult to deal elegantly with having one method respond to more
> than verb like I could if I could write:
>
> @GET
> @POST
> def foo(self):
> # Do stuff for page foo, if it is GET or POST; PUT and DELETE not
> allowed!
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list
Cross platform installer builder for Python? (like IzPack for Java)
Hi, I'm looking for an installer builder similar to IzPack (which is based on Java). Isn't there anything like that in the Python world? Extra points, if GTK+ or wxWindows is used... TIA! -- http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
andrew cooke wrote: Andre Engels wrote: On Wed, Mar 25, 2009 at 4:21 PM, andrew cooke wrote: i will go against the grain slightly and say that "len" is probably the best compromise in most situations (although i admit i don't know what [...] but i may be wrong - are there any containers (apart from pathological hand-crafted examples) that would not define __len__()? When writing my answer, I thought of generators, but I now find that those will have boolean value 'true' whether or not they have something to generate, so they will go wrong under either method. The same holds for iterators. So for now I can't find any good example. actually, the implication of what you said is probably worth emphasising to the original poster: often you don't need to test whether a list is empty or not, you simply iterate over its contents: for x in foo: # do something this will then work with lists, tuples, sets, but also with iterators and generators (which would give incorrect results in a test). in all cases, "do something" will not happen if there are no data to process. Now it would be nice to allow iteration over others too, like None . a = None for item in a : do_something_with_item I created a Null object for that, but that gives all kind of problems with i.e. configobj. cheers, Stef andrew -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Threading and tkinter
On Mar 7, 9:40 am, Jani Hakala wrote:
> > After reading the docs and seeing a few examples i think this should
> > work ?
> > Am I forgetting something here or am I doing something stupid ?
> > Anyway I see my yellow screen, that has to count for something :)
>
> I have been using the following scheme:
> - Pass the root object to the thread object when creating the object
> - Define a event_handler: root.bind('<>', evt_handler) in
> the main thread.
>
> - When the thread has done something that the GUI part should now
> about, signal an event in the thread:
> root.event_generate('<>') (no other arguments)
>
> - Call a method of the thread object in the event handler e.g. to get
> some data from a queue object.
>
> This ensures that only the main thread accesses Tkinter-related things.
>
Thanks :-)
PS why does the first example leave a running process (dos box) open
when you close the gui and yours not ?
Also root.after can make the program crash if the threat is waiting
for com1 response.
Speaking of com1 ports, for some reason I have to start up some other
serial terminal app and close it again before the device is returning
data to the python app ? Do you need to send something to the com1
device first ?
---first example--
from tkinter import *
from threading import Thread
from time import sleep
class Weegbrug(Thread):
def __init__(self):
Thread.__init__(self)
self.x=0
def run(self):
while True:
self.x=self.x+1
sleep(0.5)
w = Weegbrug()
w.start()
def display():
v.set(w.x)
root.after(500, display)
root = Tk()
v = StringVar()
txt = Label(root, textvariable=v, width=800, height=600, bg='yellow',
font=('Helvetica', 300))
txt.pack(expand=YES, fill=BOTH)
root.title('Weegbrug')
root.overrideredirect(1)
root.geometry('%dx%d+0+0' % (root.winfo_screenwidth(),
root.winfo_screenheight()))
root.after(500, display)
root.mainloop()
from tkinter import *
from threading import Thread
from queue import Queue
from time import sleep
--second example-
class Weegbrug(Thread):
def __init__(self, gui):
Thread.__init__(self)
self.gui = gui
self.queue = Queue()
def run(self):
while True:
with open('com1', 'w+') as f:
for line in f:
self.queue.put(line)
self.gui.event_generate('<>')
time.sleep(0.5)
def get_line(self):
return self.queue.get()
def evt_handler(*args):
v.set(w.get_line())
r = Tk()
r.title('Weegbrug')
r.overrideredirect(1)
r.geometry('%dx%d+0+0' % (r.winfo_screenwidth(),r.winfo_screenheight
()))
r.bind('<>', evt_handler)
v = StringVar()
v.set('0')
t = Label(r, textvariable=v, width=100, bg='yellow', font=
('Helvetica', 300))
t.pack(expand=YES, fill=BOTH)
w = Weegbrug(r)
w.start()
r.mainloop()
--
http://mail.python.org/mailman/listinfo/python-list
Re: minor revision encoded in SONAME in libpython.so
On Mar 24, 2:23 pm, "Martin v. Löwis" wrote: > > So, for example, if I upgrade to libpython2.6.so.1.1 > > How do you do that? There won't ever be such a library. They > will always be called libpython2.6.so.1.0. > > So no, no minor revision gets encoded into the SONAME. Then what's the significance of the .1.0 at the end of the SONAME? Is it just nipples for men? (I hope no one objects to my extending the Monty Python theme to Time Bandits). -- http://mail.python.org/mailman/listinfo/python-list
Re: Relative Imports, why the hell is it so hard?
En Tue, 24 Mar 2009 21:57:12 -0300, Istvan Albert escribió: On Mar 24, 3:16 pm, "Gabriel Genellina" wrote: Did you know, once a module is imported by the first time yeah yeah, could we not get sidetracked with details that are not relevant? what it obviously means is to import it in all of your modules that need to access to relative paths Uh? You posted a module containing a function and some code that modifies sys.path. I imagine you are interested in those side effects in sys.path -- which will only happen the first time it is imported. Isn't it relevant? I don't understand, how is this supposed to help relative imports? That's only because you have not had to deal with the problem that it solves. But I had to deal with the problem that it *creates*, even before relative imports existed, and it's a lot worse. Bindly inserting directories into sys.path can easily confuse the import systemn confuse the import system? what the heck does that mean? You either have a path in the sys.path or not. FWIW it is far cleaner than doing a relative import that does not work correctly. Others have posted the way to execute modules inside a package. For the problem of adding random directories to sys.path, see: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ed47d8e31ca3d411/e22039a2cf166f42?#e22039a2cf166f42 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
Raymond Hettinger wrote: On Mar 25, 7:38 am, srinivasan srinivas wrote: For ex: to check list 'A' is empty or not.. if A == []: if A.count == 0: if len(A) == 0: if not A: PEP 8 recommends the latter. Raymond I can't seem to find where this recommendation is mentioned or implied. Personally I would go for the len version for the sole reason that its immediate clear what it is what I am trying to do here. So that when I reread my code a couple of weeks later I don't have to think, eh was A a bool, oh no I was checking if that list had content in it. But that could be just me though :-) YMMV -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: time.strptime() undocumented difference python 2.5.1>2.5.2
On Mar 25, 7:38 pm, MRAB wrote:
> TYR wrote:
> > A server that runs one of my programs was upgraded to Debian Lenny
> > last night, which moved it from Python 2.4.4 to 2.5.2. This caused
> > immediate trouble. At one point, data is parsed from a Web page, and
> > among other things a time date group is collected. This is in a nice
> > human readable format, but I want it in RFC 822 format because it's
> > going to be used in an outbound GeoRSS feed and it's a requirement.
>
> > So the time group is split up with a regex, merged into one string,
> > and fed to time.strptime() with a fitting format, then passed to
> > Utils.formatdate() and used. The time group looks like this:
> > 25/03/2009 21:05:00
>
> > Code:
> > if airline not in whitelist:
> > retime = re.split('[-\s:/]', rawtime)
> > timeinput = ''.join(retime)
> > t = time.strptime(timeinput, "%d %m %Y %H %M %S")
> > timeout = Utils.formatdate(t)
>
> > Error:
> > Traceback (most recent call
> > last):
> > File "/home/yorksranter/vfeed-data/bothv7.py", line 46, in
> >
> > t = time.strptime(timeinput, "%d %m %Y %H %M
> > %S")
> > File "/usr/lib/python2.5/_strptime.py", line 330, in
> > strptime
> > (data_string,
> > format))
> > ValueError: time data did not match format: data=25032009210500 fmt=
> > %d %m %Y %H %M %S
>
> > Weirdness:
>
> > Python 2.5.2 (r252:60911, Jan 4 2009, 21:59:32) #the
> > server
> > [GCC 4.3.2] on
> > linux2
> > Type "help", "copyright", "credits" or "license" for more
> > information.
> timeinput = '25032009210500'
> import time
> t = time.strptime(timeinput, "%d %m %Y %H %M %S")
> > Traceback (most recent call
> > last):
> > File "", line 1, in
> >
> > File "/usr/lib/python2.5/_strptime.py", line 330, in
> > strptime
> > (data_string,
> > format))
> > ValueError: time data did not match format: data=25032009210500 fmt=
> > %d %m %Y %H %M %S
>
> > But
>
> > Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57) #the laptop
> > [GCC 4.2.1 (SUSE Linux)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> import time
> timeinput = '25032009210500'
> t = time.strptime(timeinput, "%d %m %Y %H %M %S")
> print t
> > (2009, 3, 25, 21, 5, 0, 2, 84, -1)
>
> > Docs (http://docs.python.org/library/time.html#time.strptime) say:
> > Parses a string representing a time according to a format. If I send
> > it through str() to make absolutely sure it is a string I get the same
> > error.
>
> > I note from the changelog that there was a change affecting
> > time.strptime()...(http://www.python.org/download/releases/2.5.2/
> > NEWS.txt)
>
> > - Bug #1730389: Have time.strptime() match spaces in a format argument
> > with
> > ``\s+`` instead of ``\s*``.
>
> > - Bug #1290505: Properly clear time.strptime's locale cache when the
> > locale
> > changes between calls. Backport of r54646 and r54647.
>
> > I don't see that either of these should break it, but it's got to be a
> > suspect.
>
> I think it's due to bug #1730389. This says that a space in the format
> string should match _at least one_ space in the string it's parsing.
> Your format is "%d %m %Y %H %M %S" (it contains spaces) but your string
> is "25032009210500" (it doesn't contain spaces), hence the failure.
>
> I suggest you change:
>
> timeinput = ''.join(retime)
>
> to:
>
> timeinput = ' '.join(retime)
>
> It'll make the string a little clearer anyway: "25 03 2009 21 05 00".
Thank you; that was indeed the issue, which helped me discover that
email.Utils.formatdate() stopped accepting struct_times in the same
change and started wanting floats.
--
http://mail.python.org/mailman/listinfo/python-list
Re: What way is the best to check an empty list?
Martin P. Hellwig wrote: > Raymond Hettinger wrote: >> On Mar 25, 7:38 am, srinivasan srinivas >> wrote: >>> if not A: >> PEP 8 recommends the latter. > I can't seem to find where this recommendation is mentioned or implied. it's the next-to-last sub-item, just before the references. http://www.python.org/dev/peps/pep-0008/ andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Relative Imports, why the hell is it so hard?
On Mar 25, 1:07 am, Kay Schluehr wrote: > On 25 Mrz., 05:56, Carl Banks wrote: > > > > > > > On Mar 24, 8:32 pm, Istvan Albert wrote: > > > > On Mar 24, 9:35 pm, Maxim Khitrov wrote: > > > > > Works perfectly fine with relative imports. > > > > This only demonstrates that you are not aware of what the problem > > > actually is. > > > > Try using relative imports so that it works when you import the module > > > itself. Now run the module as a program. The same module that worked > > > fine when you imported it will raise the exception: > > > PEP 366 addresses this issue. > > > Not the best solution, one that still involves boilerplate, but it is > > much less of a hack than your version, and at least it has the > > blessing of the language designers so it won't unceremoniously break > > at some point. > > A workaround that is hardly acceptable when we are working with / > debugging 3rd party packages. Python was simpler without relative > imports and occasional ambiguity resolutions by means of absolute > imports. Unfortunately Brett Cannons reconstruction of import > semantics comes a little late for Python 3 and I suppose we have to > live with the current mess Out of curiosity, is there anything--aside from explicit relative imports--worked before but doesn't now? The issue Istvan is talking about exists even with the implicit imports. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: file open fails.
[email protected] wrote: Wouldn't it be easier just to avoid the windows slashes altogether and stick to the posix: title = 'c:/thesis/refined_title.txt' Well, yes in a way, but lots of places in windows you can get a copy of a full file spec into the cut buffer, so you cut/paste rather than type. If you do that, you get the backslashes (and you better be prepared for that by using r'' to paste into). --Scott David Daniels [email protected] -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem Python 2.6.1 vs 2.6 & pyWin32
On 25/03/2009 11:41 PM, John Machin wrote: This all sounds good. I presume that "this version of distutils" means the 2.6.2/3.1 version. Yep. In the meantime, until 2.6.2 final is released, is my suggestion of using Python 2.5 to build installers reasonable? Yep. Is there a better approach? Not that I'm aware of - hence the fixing of the installer to avoid the crt completely. BTW, the user with the problem has not only confirmed that he did indeed receive the misspelled German version of the error message :-) but also has successfully installed the package using a 2.5-built installer that I provided. It's curious that out of over 250 downloads of the 2.6-built installer, there's been only 1 report of the installer not working. IIRC, the installer would work OK if a 'public' or shared copy of the vc runtime was installed - but it would seem unusual that 249 out of 250 people would have that... Cheers, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe - win32com - GetGeneratePath Error
On 26/03/2009 2:19 AM, Christopher Panici wrote:
Has anyone solved the GetGeneratePath Error?
I am getting this when I use
win32com.client.DispatchWithEvents('iTunes.Application',
customEventHandler). I have drilled down to the file and found it in
that path.
Does anyone have any ideas?
HERE IS THE ERROR. If anyone is good at this please email me back.
---
Traceback (most recent call last):
File "AppleHackGUI.pyw", line 376, in
File "Main.pyc", line 29, in __init__
File "win32com\client\__init__.pyc", line 250, in DispatchWithEvents
File "win32com\client\gencache.pyc", line 520, in EnsureModule
File "win32com\client\gencache.pyc", line 287, in MakeModuleForTypelib
File "win32com\client\makepy.pyc", line 256, in GenerateFromTypeLibSpec
File "win32com\client\gencache.pyc", line 141, in GetGeneratePath
IOError: [Errno 2] No such file or directory:
'C:\\Users\\Neech\\Documents\\PythonProjects\\AppleHack\\src\\dist\\library.zip\\win32com\\gen_py\\__init__.py'
This error is caused by a py2exe application; such applications are
unable to generate .py files from COM typelibs, but they are capable of
generating them at build time and distributing them with the app. You
should ask whoever put the application together to read the py2exe docs
to learn how to embed the generated files for ITunes directly inside the
app.
Cheers,
Mark
--
http://mail.python.org/mailman/listinfo/python-list
