Re: how to interact with Windows cmd?
Not sure but have you tried using functions from the os library? For example you could use execl() to execute your commands and pipe the output somewhere-stdin in your case. -- http://mail.python.org/mailman/listinfo/python-list
Re: stuck in files!!
The best you can do is pipe a string to a .txt document then pipe it again to a wordpad document. You should be able to do that easily with file and open() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print a number as if in the python interpreter?
Use repr() print(repr(sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]))) -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie ``print`` question
Well you can convert the ints to str then concatenate them. print "1" + "2" -- http://mail.python.org/mailman/listinfo/python-list
Re: stuck in files!!
Didn't see the post date on my reader haha. Sorry about that. -- http://mail.python.org/mailman/listinfo/python-list
pretty cool way of posting
30 lines of bash with 1 py3 line. all u need for usenet ! -- https://mail.python.org/mailman/listinfo/python-list
pretty cool way of posting 2
30 lines of bash with 1 py3 line. all u need for usenet ! -- https://mail.python.org/mailman/listinfo/python-list
Multiple versions
I need to install both 2.3 and 2.4 on my Win2000 system. Can someone please give me a pointer as to how to do this? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple versions
Thank you for your reply! Is there a simple way to change the .py/.pyw associations? Like a registry setting I can "toggle"? Or are there lots of other things involved, system directory libraries etcetera? "Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] [Me] > I need to install both 2.3 and 2.4 on my Win2000 system. Can someone please > give me a pointer as to how to do this? Thanks! It depends on your other requirements. The simple answer is: just install them (in different directories, eg c:\python23, c:\python24), installing last the one which you want your .py/.pyw files to be associated with. If you have more specific requirements concerning shared modules and so on, the answer might be slightly different. Personally, these days, I install the versions I want (I have 2.1 - 2.4 on this machine) and reinstall external modules for each version. My own modules I keep in a Subversion repository and update as needed. This avoids slight messiness with mismatched .pyc files, I find. TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple versions
This will work fine for me Tim, thank you for your time! "Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] (Just to keep things readable, I've reordered the posts top-to-bottom chronologically. And "Me" is the cognomen of the original poster, not simply a redundant personal pronoun!) [Me] > I need to install both 2.3 and 2.4 on my Win2000 system. > Can someone please > give me a pointer as to how to do this? Thanks! [Tim Golden] > ... The simple answer is: just install > them (in different directories, eg c:\python23, > c:\python24), installing last the one which > you want your .py/.pyw files to be associated with. [Me] > Thank you for your reply! Is there a simple way to > change the .py/.pyw associations? Like a registry > setting I can "toggle"? Or are there lots of other > things involved, system directory libraries etcetera? Assuming that you're not doing anything fancy with system or Python paths -- and I guess from the tenor of your questions that you're not -- then it's just the same as changing any other file association on Windows. There was a thread on this subject fairly recently, but in essence you can either use the File Associations tab on Explorer (on XP it's under Tools > Folder Options > File Types) or you can use the command line equivalent: FTYPE Python.File="C:\Python24\python.exe" "%1" %* replacing c:\python24 by whatever is appropriate. If you really wanted to do things which involved testing your programs against different versions of Python, which I imagine might be your aim, then you probably want either to write some sort of batch file wrapper (search c.l.py for some examples of this in the past) or to use a MoveablePython installation: http://www.voidspace.org.uk/python/movpy/ which is designed for this kind of things (according to their introduction). TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
error
whenever i try and run my Python GUI, my computer thinks for a sec, then drops the process, without ever displaying the window. the command prompt window seems to work fine, but the IDLE GUI won't start. i'm running Windows 2K professional and python 2.4, so any advice help would be appreciated. i've already tried reinstalling and use a thread response, as the e-mail on this account is bogus. -- http://mail.python.org/mailman/listinfo/python-list
problem with win32file.RemoveDirectory
Hello python world.
Since yesterday I'm using Python 2.4/PythonWin (build 203) on my Win98
system.
My problem - that did not occured in the previous version Python
2.3.4/PythonWin (build 163) - is the following:
The command i. e. 'win32file.RemoveDirectory("C:\\Python 2.4\\folder")'
causes the error message:
Traceback (most recent call last):
File "C:\Python24\remove.py", line 2, in ?
win32file.RemoveDirectory('C:\\Python24\\folder')
error: (120, 'RemoveDirectoryW', 'This function is only valid in Win32
mode.')
The new documentation tells me that RemoveDirectory "is implemented
using RemoveDirectoryW."
Does that mean a "NT/2000 Unicode specific version" and the
impossibility using this function on Win98?
Thanks for your help,
Johannes
--
http://mail.python.org/mailman/listinfo/python-list
buggy python interpretter or am I missing something here?
I'm writing a linux daemon in python 2.x to process batches of GPS/GIS
data and I'm running into something that seems to break the expected
program flow in a REALLY BAD WAY.
Consider the attached template script and execute it with the -h option.
It is falling through to the except: clause even though try to manually
exit with sys.exit(0). However, if I insert a "raise" into the except
clause then the sys.exit(0) executes properly.
See the attached code and output from when I run it.
Not interested in work-arounds. I want to understand why it doesn't work
as expected.
Thanks!
TCdaemon.py
#! /usr/bin/python
import sys
#
--
defaultparams={ \
"basedir": "/process", \
"inpipe": "/tmp/TCdaemonIN", \
"maxjobs":8, \
"outpipe": "/tmp/TCdaemonOUT", \
"ZZZ": 0
}
#
--
def parse_args(a,d):
l=len(a)
idx=1
try:
while (idxhttps://mail.python.org/mailman/listinfo/python-list
Re:buggy python interpretter or am I missing something here?
On Mon, 27 Jan 2014 00:36:20 -0500, Dave Angel wrote: > sys.exit() raises an exception, and you're deliberately eating > that exception. > I can buy that sys.exit (may) be throwing an exception...My point of contention isn't that I may be throwing one, but why would a subsequent "raise" in the except: clause cause the point of program execution to jump back up to the sys.exit(0) and then function correctly. This seems to be a violation of the programming semantics of python as I understand them...coming from an old fart c++ programmer where bare catch() is totally acceptable and common form. > > Bare except is almost never a good idea. It's going to intercept > the exit exception, plus control C, syntax errors and others. > Which you'd have known if you printed the exception code. > > > If you're going to catch an exception, be specific. Otherwise > expect the unexpected. > > > There is a hierarchy of exception classes, so you could catch a > fairly generic class. But you do need to distinguish. I'll take your point of "almost a never good idea" under consideration and agree that if I was writing something for production use I'd be more comprehensive, but I really don't care what exceptions are raised at this point ... until I've tested with bunches of input data and see that it does break and under what circumstances. But...it still doesn't explain why/how a raise in the except: clause can recover the point of program execution back to the sys.exit(0) that threw the exception. Are you saying that the programming semantics of try/except are different in python than they are in c++? My expectation being that when an exception occurs program control jumps to the except: and then continues below without ever going back to the code that threw the exception in the first place...because that's exactly what it appears to be doing? Are except: clauses in python more synonymous with the old BASIC "GOSUB" or "ON ERROR GOSUB" statement rather than following the c++ semantics? kind regards -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On Sun, 26 Jan 2014 21:04:57 -0800, Gary Herron wrote: > > Never *ever* have a bare except like that. If it gets invoked, you have > no idea why. A simple typo like ixd instead of idx or a(idx) instead > of a[idx] would raise an exception but give you no idea why. > > Do >try: >... >except Exception,e: >print e > at the absolute minimum. > (Python 3 syntax would differ slightly, but the advice is the same.) > > Perhaps printing a traceback along with the exception would help. Add > traceback.print_exc() So here's the clencher without debating the merits bare except: since a bare catch(...) is totally acceptable in the c++ world. When I have except: by itself the program fails...but simply adding the "except Exception,e: " causes the program to work correctly. To me that signifies an undefined behavior of the python specification, or at least bad behavior of the python interpreter I'm using. If you can syntactically use a bare except: without generating an invalid syntax error then it should have a well defined and predictable outcome. If in fact the "except Exception, e:" is what's required then a bare except shouldn't be considered valid syntax at all, right? kind regards -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On Mon, 27 Jan 2014 01:21:41 -0500, Terry Reedy wrote: > On 1/27/2014 12:04 AM, Gary Herron wrote: > >> Do >>try: >>... >>except Exception,e: >>print e >> at the absolute minimum. >> (Python 3 syntax would differ slightly, but the advice is the same.) > > The 'python 3' syntax >except Exception as e: > works in 2.7 and perhaps 2.6. So use it unless you need compatibility > with even earlier versions. My point of contention isn't so much about what specific syntax I should be using as much as it is about being allowed to use a syntax that gives erroneous results without triggering a syntax violation. If the bare except: clause is syntactically legal then it should yield deterministic results based on a well defined language specification, right? It's looking very much like "except:" is undefined behaviour. kind regards -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
In any case, thanks for the answers guys. I'm satisfied that the except: syntax yields undefined behavior, and in my mind it shouldn't be syntactically allowed then. Updating to Exception,e or Exception as e fixes the problem. -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On Mon, 27 Jan 2014 00:47:13 -0600, Zachary Ware wrote: > You've missed the point here. sys.exit() *does* raise an exception: > SystemExit, a subclass of BaseException. In fact, you can implement > sys.exit in pure Python like so: > > def exit(status): > raise SystemExit(status) > > Your bare 'except:' catches that SystemExit along with any other > possible exception; the bare 'raise' in the except clause just re-raises > the same SystemExit, which then does what you meant for it to do in the > first place. Well that does change things a bit and makes perfect sense now. Thx! > And, please take this positively, but from your posted code it's fairly > apparent that Python is not your native tongue :). Correct. The barbarians invaded my homeland and forced me to speak their wicked incantations. I'm a c/c++ guy through and through with a sprinkling of the ancient tongues like algol, LSI-11 and Z80 assembler, fortran-4, etc. My python stuff is all rapid application development for personal projects. If I need to do anything serious I take the time to do it in C+ +. > For instance, you > don't need the backslashes in your defaultparams assignment; the parser > knows it needs to keep looking on subsequent lines when it hasn't found > the closing '}' yet. It's the intendation specific requirements that throw me. I haven't seen such a hork since RPG. ;^) > Also, you can iterate over a (sys.argv) in a for > loop, replacing 'l', 'idx', and the while loop; something like > > for arg in a: > if arg == '-h': > print help # help being defined elsewhere... > elif arg == '-hh': > # no really, print help print 'help' Understood, except that some parameters take multiple elements...thus why I manually reference the indexes. > And the big one, argument parsing is a solved problem in Python. Check > out the argparse module in the standard library (or if you're using an > older version of Python, try either optparse or getopt. It's really a > thrice-solved problem ;)). Yup. Every language and platform has multiple arg parsing libraries. Didn't feel like taking the time to research any since most of my python ramblings are usually pyQT4 bindings to QT4 gui and postgresql apps. > > I hope I've been of some help, Pointing out that sys.exit() raises a low level exception was the point I was missing. Thx! -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On Sun, 26 Jan 2014 23:03:51 -0800, Gary Herron wrote: found the part I was missing based on another response. Didn't realize that sys.exit() triggered an instance of "BaseException" and that explains the weird behavior. thx! -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On Sun, 26 Jan 2014 23:12:18 -0800, Gary Herron wrote: > On 01/26/2014 10:46 PM, me wrote: >> In any case, thanks for the answers guys. I'm satisfied that the >> except: >> syntax yields undefined behavior, and in my mind it shouldn't be >> syntactically allowed then. >> >> Updating to Exception,e or Exception as e fixes the problem. >> >> > That's an irksome habit you have there, this jumping to (incorrect) > conclusions so quickly. We'd like to get to the bottom of this. (And > correct your mis-interpretations while we're at it :-)But we need to > see your test *and* the results. > > Gary Herron Problem solved. I understand what was happening now with the "raise" following the bare except: Since this code is for a personal research project I'm not as concerned about code quality as I would be if I was getting paid to write production code...and if it was production code I'd only prototype a proof-of-concept in python and then rewrite in c++. The project is to take advantage of all 16 CPU cores to process A LOT of GPS data for a 3d map-making and visualization project. Now my bottleneck may end up being the python global lock when doing concurrent processing...but we'll see. -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On Sun, 26 Jan 2014 23:17:29 -0800, Ethan Furman wrote: > On 01/26/2014 10:46 PM, me wrote: >> >> [...] I'm satisfied that the except: syntax yields undefined behavior, >> and in my mind it shouldn't be >> syntactically allowed then. > > Two points: > >1) Python is not C++ > >2) You asked for help; you received it. Coming back > with an attitude of "Python must be broken, I'll work around it" > is going to quickly lose you the support of those willing to help > again. Whatever...lighten up dude! -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On Mon, 27 Jan 2014 20:01:33 +1100, Chris Angelico wrote: > On Mon, Jan 27, 2014 at 6:44 PM, me wrote: >> On Sun, 26 Jan 2014 23:17:29 -0800, Ethan Furman wrote: >> >>> On 01/26/2014 10:46 PM, me wrote: >>>> >>>> [...] I'm satisfied that the except: syntax yields undefined >>>> behavior, >>>> and in my mind it shouldn't be >>>> syntactically allowed then. >>> >>> Two points: >>> >>>1) Python is not C++ >>> >>>2) You asked for help; you received it. Coming back >>> with an attitude of "Python must be broken, I'll work around it" >>> is going to quickly lose you the support of those willing to >>> help again. >> >> >> Whatever...lighten up dude! > > When you use a language, you should be working with it, not fighting > against it. It doesn't do to complain that REXX ought to have IEEE > floating-point semantics, or that 8086 assembly language really would > benefit from a native hashtable type. Python works a certain way, and > part of that is its use of exceptions - which are integral to the > language, rather than being (as in C++) somewhat tacked-on. Assuming > that anything that isn't the way you expect it is inherently broken, and > saying so on a mailing list, is a good way to alienate those who are > offering you help for no reimbursement... and "lighten up dude" doesn't > help. > > ChrisA You feel better now that you too have vented? I had a productive discussion with a couple of top level posters who helped me solve my problem and they receive appropriate kuddos. Now it seems that some lonely individuals who maybe just want some attention are coming out of the woodwork. The thread is done so lets give it a rest. The condescending attitude about proper USENET tech help is just as annoying as perhaps my "opinions" seem. If someone is so sensitive as to not be able to discuss a technical matter without making it personal or seeing it as an attack against their religion then I neither want nor need their input. There are plenty of technical resources in the world that don't require idol worship. Regards -- https://mail.python.org/mailman/listinfo/python-list
Re: how to make the below code look better
On 2015-12-02, Ganesh Pal wrote:
> if not os.path.ismount("/tmp"):
>sys.exit("/tmp not mounted.")
> else:
> if create_dataset() and check_permission():
> try:
> run_full_back_up()
> run_partial_back_up()
> except Exception, e:
> logging.error(e)
> sys.exit("Running backup failed")
> if not validation_errors():
> sys.exit("Validation failed")
> else:
> try:
> compare_results()
> except Exception, e:
>logging.error(e)
>sys.exit("Comparing result failed")
Apart from what already mentioned (indentation, assumptions on
environment):
> 1. if create_dataset() and check_permission():
> Iam assuming that if statement will be executed only if both the
> functions are true ?
Yes, this is the meaning of 'and'.
Notice how functions are always true, but the result of the function call
might not be.
- create_dataset is a function.
- create_dataset() is a function call.
> 2. Can I have a if statement within if else ? , some how I feel its messy
You are searching for `elif`.
--
https://mail.python.org/mailman/listinfo/python-list
Re: regarding download issues from sharepoint site
On 2015-12-02, Arpit Arya wrote: > please help me out http://catb.org/~esr/faqs/smart-questions.html#beprecise -- https://mail.python.org/mailman/listinfo/python-list
Re: python message
On 2015-12-02, [email protected] wrote: > I do not understand this message. Atached it my code. I'm new to Usenet, so maybe it's my fault. But I can't find any attachment in your message. Would you mind to post the code? -- https://mail.python.org/mailman/listinfo/python-list
Re: subprocess check_output
On 2016-01-02, Chris Angelico wrote: > down to "whoops, I forgot to save the file" or "whoops, I was in the > wrong directory"... Amen, bro. Exceptionally true if you ever need for some reason to put your code in another directory, but you forget to close the files in your editor. :D -- https://mail.python.org/mailman/listinfo/python-list
Re: What use of these _ prefix members?
On 2016-01-10, Peter Otten <[email protected]> wrote: class Derived(Base): > ... def _init(self, x): > ... super()._init(x) > ... print("do something else with", x) > ... Derived(42) > do something with 42 > do something else with 42 ><__main__.Derived object at 0x7f8e6b3e9b70> > I think you are doing inheritance wrong. AFAIK you should call directly the __init__() of the parent class, and pass *args and **kwargs instead. Except for that, yes, the _init would be conventionally private. Not enforced by name mangling though. -- https://mail.python.org/mailman/listinfo/python-list
Re: Powerful perl paradigm I don't find in python
On 2016-01-15, Ulli Horlacher wrote:
> Charles T. Smith wrote:
>> while ($str != $tail) {
>> $str ~= s/^(head-pattern)//;
>> use ($1);
>> }
>
> use() is illegal syntax in Perl.
Actually it is not. OP is defnitely thinking of `use` as a placeholder for
some general use of the value $1.
In fact, according to the documentation of perl,
use Module LIST
is equivalent of
BEGIN{ require Module; Module->import(LIST); }
For the rusty perl users, the code in `BEGIN` blocks are executed "as soon
as possible", that is before the remaining part of the code, and in order
of definition.
The idea is that you want to import all modules before running the code.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Please help - Python role in Emeryville, CA - Full-time - $100K+
On Thu, 18 Dec 2014 00:08:18 +, Jared E. Cardon wrote: > Hi, > > I found your Python group on Google+ and I'm searching for someone with > 3+ years of Python development experience for a full-time position in > California. Salary north of $100K and working for an amazing company. > Ideally I'd like to find someone who is nice, plugged into the movie and > comic culture, and very skilled at python and web application > development. > > If you know of anyone local to the area who would be interested please > put me in touch with them. Feel free to post my request on the group > page. > > Thank you, > Jared Except that sisinc is a body shop and that 100k is low for any real programming job in California. Used to be that contracting work paid W2 at 150% of what you would make as a client direct hire. Now the pimps look at you with a straight face and expect you to work for similar or less money than direct hire, with minimal to no benefits, and absolutely no job security. -- https://mail.python.org/mailman/listinfo/python-list
Re: error with Firefox Binary 'The browser appears to have exited'
Have you tried specifying the location of Firefox binary explicitly ?
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary =
FirefoxBinary('C:\Users\aplusk\Documents\FirefoxPortable\App\Firefox\\firefox.exe')
browser = webdriver.Firefox(firefox_binary=binary)
--
https://mail.python.org/mailman/listinfo/python-list
creating a pattern using a previous match and a count of the number of '('s in it
I'm new to regexs and trying to get a list of all my C++ methods with balanced
parenthesis as follows.
#find all c++ method prototypes with a '::' in the middle
#upto and including the 1st closing parenthesis
pattern_upto_1st_closed_parenth = re.compile('\w+::\w+\([^)]*\)')
match_upto_1st_closed_parenth=
re.findall(pattern_upto_1st_closed_parenth,txt)
num_of_protos = len(match_upto_1st_closed_parenth)
for i in range (0,num_of_protos-1):
num_of_open_parenths = match_upto_1st_closed_parenth[i].count('(')
#expand the pattern to get all of the prototype
#ie upto the last closed parenthesis
#saying something like
pattern = re.compile(\
'match_upto_1st_closed_parenth[i]+\
(([^)]*\)){num_of_open_parenths-1}'\
)
#
#HELP!! I'm not sure how to incorporate:
#1 'match_upto_1st_closed_parenth[i]' into the above extended pattern???
#2 the count 'num_of_open_parenths' instead of a literal ???
#
#===
#if I could do it this sort of this would appear to offer the neatest solution
pattern_upto_last_balanced_parenthesis = re.compile('
(\w+::\w+\([^)]*\))\
([^)]*\)){\1.count('(')-1}
')
#===
Should I be using regexs to do this?
I've only put \ line extensions to separate the pattern components to assist
readability
Thx
--
http://mail.python.org/mailman/listinfo/python-list
python gui builders
Good People I do not write stuff for humans, as it has been my job to remove humans from the loop. But I have to make a front end to a component database where everything was built in Python. I have looked at the Tk stuff that is built into Python -> not acceptable. So looking at wxGlade, Boa Constructor, Python Card. Also looked at the frames/forms created with QtDesigner, which can be used by Python via pyuic. BlackAdder IDE seems to have this built-in, but am loathe to buy into another GUI tool for a single job. I have not been able to find a decent Python gui builder. The last time I did gui garbage was with Borland C++ Builder which was ok because I was only using win boxen for that project. This time I am using both Linux and Win. What Python gui builder is well supported, does not require me to learn another framework/library, and can crank out stuff for multiple platforms ? thanks much, me -- http://mail.python.org/mailman/listinfo/python-list
Re: python gui builders
Read the OP. No, read it again. sturlamolden wrote: On 16 Nov, 11:39, sturlamolden wrote: If you are fine with Microsoft only, you can use Windows Forms with MS Visual Studio and IronPython. I also forgot to mention: If you can restrict yourself to Windows, you can always use Visual Basic or Borland Delphi with pywin32. Either expose your GUI as an ActiveX to pywin32 (you have e.g. an MFC binding) or expose your Python as an ActiveX to VB/Delphi. The same approach should work (with a little bit more work) for C# and VB.NET. -- http://mail.python.org/mailman/listinfo/python-list
subset permutations
Hello all, I'm a beginner with programming. Trying to teach myself with that excellent rat book. Unfortunately I just can't seem to figure out a simple problem that has come up at my work (biology lab): let's say I have a list ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y'] . I need to generate permutations of this list. I have found plenty of code on the web to generate ALL possible permutations. What I need are all possible 4-letter permutations. I cannot seem to figure out how to modify Mike Davie's permutation generator http://www.bigbold.com/snippets/posts/show/753 to acheive this. Any help would be appreciated. Thanks DG -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: novice regular expression question
Oops!
Sorry, didn't realize that.
Thanks,
"M.E.Farmer" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> It's me wrote:
> > The shlex.py needs quite a number of .py files. I tried to hunt down
> a few
> > of them and got really tire.
> >
> > Is there one batch of .py files that I can download from somewhere?
> >
> > Thanks,
> Not sure what you mean by this.
> Shlex is a standard library module.
> It imports os and sys only, they are standard library modules.
> If you have python you have them already.
> If you mean cStringIO it is in the standard library(at least on my
> system).
> You dont have to use it just feed shlex an open file.
> py>lexer = shlex.shlex(open('myrecord.txt', 'r'))
>
> Hth,
> M.E.Farmer
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a search string
I am right in the middle of doing text parsing so I used your example as a mental exercise. :-) Here's a NDFA for your text: b 0 1-9 a-Z , . + - ' " \n S0: S0 E E S1 E E E S3 E S2 E S1: T1 E E S1 E E E E E E T1 S2: S2 E E S2 E E E E E T2 E S3: T3 E E S3 E E E E E E T3 and the end-states are: E: error in text T1: You have the words: moo, cow T2: You get "farmer john" (w quotes) T3: You get zug Can't gurantee that I did it right - I did it really quick - and it's *specific* to your text string. Now just need to hire a programmer to write some clean Python parsing code. :-) -- It's me "Freddie" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Happy new year! Since I have run out of alcohol, I'll ask a question that I > haven't really worked out an answer for yet. Is there an elegant way to turn > something like: > > > moo cow "farmer john" -zug > > into: > > ['moo', 'cow', 'farmer john'], ['zug'] > > I'm trying to parse a search string so I can use it for SQL WHERE constraints, > preferably without horrifying regular expressions. Uhh yeah. > > From 2005, >Freddie > -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a search string
"Andrew Dalke" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "It's me" wrote: > > Here's a NDFA for your text: > > > >b 0 1-9 a-Z , . + - ' " \n > > S0: S0 E E S1 E E E S3 E S2 E > > S1: T1 E E S1 E E E E E E T1 > > S2: S2 E E S2 E E E E E T2 E > > S3: T3 E E S3 E E E E E E T3 > > Now if I only had an NDFA for parsing that syntax... > Just finished one (don't ask me to show it - very clumpsy Python code - still in learning mode). :) Here's one for parsing integer: # b 0 1-9 , . + - ' " a-Z \n # S0: S0 S0 S1 T0 E S2 S2 E E E T0 # S1: S3 S1 S1 T1 E E E E E E T1 # S2: E S2 S1 E E E E E E E E # S3: S3 T2 T2 T1 T2 T2 T2 T2 T2 T2 T1 T0: you got a null token T1: you got a good token, separator was "," T2: you got a good token b, separator was " " E: bad token > :) > Andrew > [EMAIL PROTECTED] > -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a search string
"John Machin" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Andrew Dalke wrote:
> > "It's me" wrote:
> > > Here's a NDFA for your text:
> > >
> > >b 0 1-9 a-Z , . + - ' " \n
> > > S0: S0 E E S1 E E E S3 E S2 E
> > > S1: T1 E E S1 E E E E E E T1
> > > S2: S2 E E S2 E E E E E T2 E
> > > S3: T3 E E S3 E E E E E E T3
> >
> > Now if I only had an NDFA for parsing that syntax...
>
> Parsing your sentence as written ("if I only had"): If you were the
> sole keeper of the secret??
>
> Parsing it as intended ("if only I had"), and ignoring the smiley:
> Looks like a fairly straight-forward state-transition table to me.
Exactly.
> The
> column headings are not aligned properly in the message, b means blank,
> a-Z is bletchworthy, but the da Vinci code it ain't.
>
> If only we had an NDFA (whatever that is) for guessing what acronyms
> mean ...
>
I believe (I am not a computer science major):
NDFA = non-deterministic finite automata
and:
S: state
T: terminal
E: error
So, S1 means State #1..T1 means Terminal #1, so forth
You are correct that parsing that table is not hard.
a) Set up a stack and place the buffer onto the stack, start with S0
b) For each character that comes from the stack, looking up the next state
for that token
c) If it's not a T or E state, jump to that state
d) If it's a T or E state, finish
--
http://mail.python.org/mailman/listinfo/python-list
Re: arbitrary number of arguments in a function declaration
And in case it's not obvious already, you get the number of arguments that got passed down from: len(args) "Nick Coghlan" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > rbt wrote: > > How do I set up a function so that it can take an arbitrary number of > > arguments? For example, I have a bunch of expenses which may grow or > > shrink depending on the client's circumstance and a function that sums > > them up... hard coding them is tedious. How might I make this dynamic so > > that it can handle any amount of expenses? > > > > def tot_expenses(self, e0, e1, e2, e3): > > pass > > The Python Tutorial is a wonderful thing. . . > > Anyway, you can either set up your function to take a proper list, and then > discover that the sum function already exists to add up the contents of a list: > > def tot_expenses(self, expenses): >self.total_expenses = sum(expenses) > > Or, have the function take a variable number of arguments, and do the same thing: > > def tot_expenses(self, *args): >self.total_expenses = sum(args) > > Cheers, > Nick. > > -- > Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia > --- > http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Developing Commercial Applications in Python
Shaw-PTI (www.pti-us.com) uses Python in their software. See: http://www.pti-us.com/pti/news/index.cfm and search "2004 PSS/E User Group Meeting" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay > -- http://mail.python.org/mailman/listinfo/python-list
Re: Developing Commercial Applications in Python
"Richards Noah (IFR LIT MET)" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > Begging your pardon, but a better resource would be the brochure available > (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that the > program was probably (originally) written in C/C++ (using MFC for the GUI), > and now employs Python for adding modules and scripting support. Very > interesting stuff :) > > It was actually developed in Fortran some 35 years ago. Then migrated to F77. Then added a C/C++ layer to sit ontop. Then converted to API based. Then added a Python layer on top. The only thing unfortunate is that they went with MFC on the newest version. Yuck! -- http://mail.python.org/mailman/listinfo/python-list
Re: Developing Commercial Applications in Python
Well, now that they are API based, they can easily add any script language they so wish through SWIG (www.swig.org). Maybe not LISP. SNOBOL would be the right thing to do. (*NOT*) "Richards Noah (IFR LIT MET)" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > > > It was actually developed in Fortran some 35 years ago. Then migrated to > > F77. Then added a C/C++ layer to sit ontop. Then converted to API > based. > > Then added a Python layer on top. > > > > The only thing unfortunate is that they went with MFC on the newest > version. > > Yuck! > > > > Hahaha, sounds like a party to me. And they didn't even throw in a layer of > Lisp for good effort? Too bad, if you ask me :) > > -- http://mail.python.org/mailman/listinfo/python-list
Hlelp clean up clumpsy code
Another newbie question.
There must be a cleaner way to do this in Python:
section of C looking Python code
a = [[1,5,2], 8, 4]
a_list = {}
i = 0
for x in a:
if isinstance(x, (int, long)):
x = [x,]
for w in [y for y in x]:
i = i + 1
a_list[w] = i
print a_list
#
The code prints what I want but it looks so "C-like". How can I make it
more Python like?
Thanks,
--
http://mail.python.org/mailman/listinfo/python-list
Re: Hlelp clean up clumpsy code
Thanks, Steve and Nick.
Yes, that's what I need to do. I didn't know it's call "flattening" a list
structure but that's precisely what I needed to do.
Steve,
I am using 2.3 and so I will go with Nick's version.
Thanks to both for helping.
"Nick Coghlan" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> It's me wrote:
> > Another newbie question.
> >
> > There must be a cleaner way to do this in Python:
> >
> > section of C looking Python code
> > a = [[1,5,2], 8, 4]
> > a_list = {}
> > i = 0
> > for x in a:
> > if isinstance(x, (int, long)):
> > x = [x,]
> > for w in [y for y in x]:
> > i = i + 1
> > a_list[w] = i
> > print a_list
> > #
> >
> > The code prints what I want but it looks so "C-like". How can I make it
> > more Python like?
>
> Firstly, calling your dictionary "a_list" is evil. . .
>
> Secondly, explaining what you want the code to do in English is handy when
> asking for help cleaning up code (since we then know which features are
> deliberate, and which are accidental implementation artificacts).
>
> If I'm reading the code correctly, you want to flatten a data structure
which
> may contain either substructures or actual elements.
>
> A custom generator will do nicely:
>
> Py> def flatten(seq):
> ... for x in seq:
> ... if hasattr(x, "__iter__"):
> ... for y in flatten(x):
> ... yield y
> ... else:
> ... yield x
> ...
> Py> data = [[1,5,2],8,4]
> Py> val_to_pos = {}
> Py> for i, x in enumerate(flatten(data)):
> ... val_to_pos[x] = i + 1
> ...
> Py> print val_to_pos
> {8: 4, 1: 1, 2: 3, 4: 5, 5: 2}
>
> Not any shorter, but this version works correctly for any leaf elements
which
> don't supply __iter__ (e.g. strings), and internal elements which do (e.g.
> tuples) and the depth is limited only by the maximum level of recursion.
Don't
> try to flatten a circular structure, though :)
>
> You may not even need to write the generator, since if you have Tkinter,
that
> already supplies a near-equivalent function:
>
> Py> from Tkinter import _flatten as flatten
> Py> data = [[1,5,2],8,4]
> Py> val_to_pos = {}
> Py> for i, x in enumerate(flatten(data)):
> ... val_to_pos[x] = i + 1
> ...
> Py> print val_to_pos
> {8: 4, 1: 1, 2: 3, 4: 5, 5: 2}
>
> It even works with strings as leaf elements:
>
> Py> data = [["abc","def",2],8,"xyz"]
> Py> flatten(data)
> ('abc', 'def', 2, 8, 'xyz')
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia
> ---
> http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list
Re: Hlelp clean up clumpsy code
What's "LBYL"? Oh...Look-before-you-leap. OK. I think I understand what's going on now (I read up on generator and iterators and my head still hurts). I knew there must be a cleaner way of "walking" around in Python. I will experiment with generator more. Thanks everybody. "Jp Calderone" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > > On Tue, 04 Jan 2005 08:18:58 -0800, Scott David Daniels <[EMAIL PROTECTED]> wrote: > >Nick Coghlan wrote: > > > A custom generator will do nicely: > > > > > > Py> def flatten(seq): > > > ... for x in seq: > > > ... if hasattr(x, "__iter__"): > > > ... for y in flatten(x): > > > ... yield y > > > ... else: > > > ... yield x > > > > Avoiding LBYL gives you: > > def flatten(seq): > > for x in seq: > > try: > > for y in flatten(x): > > yield y > > except TypeError: > > yield x > > But totally messes up on error handling. Instead: > > def flatten(seq): > for x in seq: > try: > subseq = iter(x) > except TypeError: > yield x > else: > for subx in flatten(subseq): > yield subx > > to avoid catching TypeErrors from .next(). > > Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4 on Windows XP
I am running 2.3 and it's doing the same thing on my computer - except that I can't even get it to start from the command prompt. It used to work but after I switched back and forth between 2.3, and 2.4 and somewhere in between, it stopped working. I hope somebody on the list would have a clue how to fix this. "DavidHolt" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I have a problem that I see on two different machines, one running XP > SP1 and one XP SP 2. > > On both I installed Python 2.4. > > I can't seem to start IDLE. When I try to start it, I get an hourglass > cursor for a short time then nothing more happens. This happens whether > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > to launch pythonw from a command line. > > I don't have any trouble running the python command line version. > > Any ideas? > Thanks, > David Holt > Software Developer > HighJump Software, a 3M Company > -- http://mail.python.org/mailman/listinfo/python-list
win32com.client problem
I've been using the win32com module with very good success in placing data onto an Excel spreadsheet. However, whenever I have an error in my script (like mapping a non-square array onto the spreadsheet), something breaks. After fixing my error and restart the Python program again, Excel would start up a window with a "Microsoft Excel - BookX" where X is a increasing number (1,2,3,4,) instead of just 1. Then, the spreadsheet portion of the screen is hidden - I can only see the menu bars (on top). If I restart the computer, run the Python script again and Excel would behave fine and it would start with "Microsoft Excel - Book1" everytime. My guess is that there is a zombie Excel process that got stuck in the system. However I couldn't tell for sure by looking at the Process Manager list. Any idea how I can prevent this? Thanks, -- Me -- http://mail.python.org/mailman/listinfo/python-list
Re: win32com.client problem
Thanks for the reply. I will chew on this a bit. "Kartic" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi, > > 1. Put your COM invokations in a try/except loop. From my experience, > that helped me prevent, in most cases, Excel from "hanging" and having > to restart the PC too. In the except part, release the Excel (or other > COM resource) (e.g.calling workbook.Close() or excelobj.Quit(), > depending on the state of your program) > > 2. Look at > http://www.faqts.com/knowledge_base/entry/versions/index.phtml?aid=5847 > to see how to get the actual error. > > 3. Delete instances of the COM connection, RS object or whatever > win32com.client instances you create. I do this: > sheetobj = None > wbkbobj = None > excelobj = None > del sheetobj > del wbkobj > del excelobj > > 4. At the end of my scripts, I do the following during the development > stage: > ActiveComConn = pythoncom._GetInterfaceCount() > print 'Done! Active Com Connections :',ActiveComConn # Print count of > Active COM connections. > > Thank you, > --Kartic > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4 on Windows XP
In my case, there is *no* error message of any kind. When I run pythonw.exe from the python23 directory, the screen blinked slightly and goes back to the command prompt. "Jeff Shannon" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > DavidHolt wrote: > > > I have a problem that I see on two different machines, one running XP > > SP1 and one XP SP 2. > > > > On both I installed Python 2.4. > > > > I can't seem to start IDLE. When I try to start it, I get an hourglass > > cursor for a short time then nothing more happens. This happens whether > > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > > to launch pythonw from a command line. > > Maybe I'm misinterpreting you, here, but pythonw.exe is *not* IDLE. > It is, instead, a console-less version of the Python interpreter, > which can run the Python scripts for IDLE (among other things). > > My version of Python is older, but in %pythondir%/Tools/idle, there is > an idle.pyw file. Try running that. If it doesn't work, then copy & > paste any error messages (you'll probably need to run it from a > command line for this) to your next post here so that we can try to > troubleshoot a bit more effectively. > > Jeff Shannon > Technician/Programmer > Credit International > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4 on Windows XP
Thanks, Jeff. That works. "Jeff Shannon" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > > In my case, there is *no* error message of any kind. When I run pythonw.exe > > from the python23 directory, the screen blinked slightly and goes back to > > the command prompt. > > Right -- pythonw.exe is a console-less interpreter. Having no > console, it doesn't have an interactive mode, and since you didn't > give it a script to run, it simply started, found nothing to do, and > then terminated itself. > > You need to run idle.pyw, *not* pythonw.exe. The idle.pyw script runs > inside the pythonw.exe interpreter, but the latter can't do anything > without instructions. > > Jeff Shannon > Technician/Programmer > Credit International > -- http://mail.python.org/mailman/listinfo/python-list
Another PythonWin Excel question
I followed the example in http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that to add a new worksheet to an Excel workbook, you would use the workbook.Worksheets.Add() method. That works. However, the new worksheet got added *in front* of the last worksheet I was at. How can I get it to add *after*? Thanks, -- Me -- http://mail.python.org/mailman/listinfo/python-list
Re: Another PythonWin Excel question
"Kartic" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I am not sure about this but I believe you can give a parameter > after="sheet1". to Add(), like so, Add(after="sheet1"). > I get a "got an expected keyword argument 'after'" from Add(). > Unfortunately I do not have Excel installed on this machine to confirm > this. > > A tip: if you have VBA (which you should if you have Excel) installed, > lookup the Add method for the Worksheets collection. VBA will show the > code completion, with all the arguments for the method call. Try the > same for any of the methods. > Yes, I read about that but unfortunately I have no experience with VBA *at all*. :=( > Thanks, > --Kartic > -- http://mail.python.org/mailman/listinfo/python-list
Re: Another PythonWin Excel question
Ah, this work: self.xlbook.Worksheets.Add(None,sht) got it from: http://mail.python.org/pipermail/python-list/2003-September/183367.html Thanks again. -- Me "It's me" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > "Kartic" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > I am not sure about this but I believe you can give a parameter > > after="sheet1". to Add(), like so, Add(after="sheet1"). > > > > I get a "got an expected keyword argument 'after'" from Add(). > > > Unfortunately I do not have Excel installed on this machine to confirm > > this. > > > > A tip: if you have VBA (which you should if you have Excel) installed, > > lookup the Add method for the Worksheets collection. VBA will show the > > code completion, with all the arguments for the method call. Try the > > same for any of the methods. > > > > Yes, I read about that but unfortunately I have no experience with VBA *at > all*. :=( > > > Thanks, > > --Kartic > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Another PythonWin Excel question
"Marten Bauer" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > I did it yesterday like this way and it works well (part of my code): > > wb.Worksheets.Add(Count=nrMonths,After=wb.Worksheets(1)) > > As I read in MSDN you could not write After="sheet1" instead you must > use the Object of sheet1 like in my example and it works well in my > case. The Count=... statement will create n Sheets after the first worksheet > Yes, I learn that as well. The parameter to After is a Worksheet object. It appears if you don't specify any parameters, it would add it Before the current sheet. Thanks, > > By > Marten -- http://mail.python.org/mailman/listinfo/python-list
Re: Another PythonWin Excel question
Thanks, "David Bolen" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "It's me" <[EMAIL PROTECTED]> writes: > > > Yes, I read about that but unfortunately I have no experience with VBA *at > > all*. :=( > > You don't really have to know VBA, but if you're going to try to > interact with COM objects from Python, you'll find it much smoother if > you at least use any available reference information for the COM > object model and interfaces you are using. > > In the Excel case, that means understanding - or at least knowing how > to look in a reference - its object model, since that will tell you > exactly what parameters an Add method on a worksheet object will take > and how they work. > > For excel, online documentation can be found in a VBAXL9.CHM help file > (the "9" may differ based on Excel release), but it might not always > be installed depending on what options were selected on your system. In > my English, Office 2000 installation, for example, the files are located in: > c:\Program Files\Microsoft Office\Office\1033 > > You can load that file directly, or Excel itself will reference it > from within the script editor help (Tools->Macro->Visual Basic Editor, > then F1 for help). If you methods or classes and have the help > installed it'll bring in the reference. > > You can also find it on MSDN on the web, although it can be tricky to > navigate down to the right section - the top of the Office 2000 object > documentation should be available at: > > http://msdn.microsoft.com/library/en-us/odeomg/html/deovrobjectmodelguide.asp > > This is mostly reference information, but there are some higher level > discussions of overall objects (e.g., worksheets, workbooks, cells, > etc...) too. > > -- David -- http://mail.python.org/mailman/listinfo/python-list
Re: Another PythonWin Excel question
Yes, Mike,
Others pointed that out as well.
The difficulty is that they are all in VBAs. Most of them can be
translated to Python fairly easily, and some I can get from looking at the
recorded macro - but some requires quite a bit of head scratching.
For instance, I wanted to figure out how create a new window. So, I went
through the record macro process and looked at the VBA code, it says:
ActiveWindow.NewWindow
Okay. Now what???
And for switching window, it says:
Windows("Book1:1").Activate
Okay. ???
So, I look through the online information on msdn and viola! No mentioning
of that anwhere
Would be nice if there's a Python specific of itbut just dreaming...
Back to reading MSDN.
Thanks,
"Mike Thompson" wrote in message
news:[EMAIL PROTECTED]
> It's me wrote:
> > I followed the example in
> > http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that
to
> > add a new worksheet to an Excel workbook, you would use the
> > workbook.Worksheets.Add() method. That works. However, the new
worksheet
> > got added *in front* of the last worksheet I was at. How can I get it
to
> > add *after*?
> >
> > Thanks,
> >
> > --
> > Me
> >
> >
>
> Does this help?
>
>
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtomoveworksheetswithinworkbooks.asp
>
> --
> Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: Another PythonWin Excel question
Okay, thanks. That helps a lot.
"Mike Thompson" wrote in message
news:[EMAIL PROTECTED]
> It's me wrote:
> > Yes, Mike,
> >
> > Others pointed that out as well.
>
> For good reason.
>
> >
> > The difficulty is that they are all in VBAs. Most of them can be
> > translated to Python fairly easily, and some I can get from looking at
the
> > recorded macro - but some requires quite a bit of head scratching.
> >
> > For instance, I wanted to figure out how create a new window. So, I
went
> > through the record macro process and looked at the VBA code, it says:
> >
> > ActiveWindow.NewWindow
>
> app.ActiveWindow.NewWindow()
>
> >
> > Okay. Now what???
> >
> > And for switching window, it says:
> >
> > Windows("Book1:1").Activate
>
> app.Windows.Item("Book1:1").Activate()
>
> -
>
> from win32com.client import Dispatch, constants
>
> app = Dispatch("Excel.Application")
> app.Visible = True
>
> workbook = app.Workbooks.Add()
>
> defaultWorksheet = workbook.Worksheets(1)
>
> app.ActiveWindow.NewWindow()
> app.ActiveWindow.NewWindow()
>
> # grab the capation (like 'Book1:1') from one of the windows
> thridWindowsCaption = app.Windows[2].Caption
>
> print thridWindowsCaption
> app.Windows.Item(thridWindowsCaption).Activate()
>
>
>
> Sometimes its useful to look in the file generated by makepy. It details
> all the classes and their methods AND there are annotations in the form
> of comments. Having said that, if you've never looked in a makepy
> generated module before, you're in for a shock - it takes a while
> before you figure out what you are looking at.
>
> When you get stuck, trial & error and a good debuger are your friend.
>
> --
> Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: sorting on keys in a list of dicts
What does it mean by "stability in sorting"? Can somebody please give a sample for using the code posted? I am a little lost here and I like to know more about the use of keys Thanks, "Nick Coghlan" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Jeff Shannon wrote: > > I suppose that your version has the virtue that, if the sortkey value is > > equal, items retain the order that they were in the original list, > > whereas my version will sort them into an essentially arbitrary order. > > Is there anything else that I'm missing here? > > Stability in sorting is a property not to be sneezed at - it means switching to > sorting by a second key gives the effect of "sort by key 1, then by key 2", > whereas that doesn't hold with an unstable sort algorithm. If you've ever used > an application with an unstable sorting process and that only allows sorting a > table on one column at a time, you'll appreciate the frustration that can cause :) > > Also, it's required to match the behaviour of the Python 2.4 version (which gets > to take advantage of the stability of the builtin sort). > > Cheers, > Nick. > > -- > Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia > --- > http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: else condition in list comprehension
> z = [i + (2, -2)[i % 2] for i in range(10)] But then why would you want to use such feature? Wouldn't that make the code much harder to understand then simply: z=[] for i in range(10): if i%2: z.append(i-2) else: z.append(i+2) Or are we trying to write a book on "Puzzles in Python"? -- http://mail.python.org/mailman/listinfo/python-list
Re: complex numbers
For those of us that works with complex numbers, having complex number as a natively supported data type is a big advantage. Non-native add-ons are not sufficient and lead to very awkward program code. "Jürgen Exner" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > [EMAIL PROTECTED] wrote: > > #python supports complex numbers. > [...] > > So? > The world would come to a halt if all of a sudden nobody understands complex numbers anymore. :-) > > # Perl doesn't support complex numbers. But there are packages that > > supports it. > > The Math::Complex module is part of the standard installation already, no > need for any "packages" (whatever that might be). > Did you check "perldoc Math::Complex" > > NAME > Math::Complex - complex numbers and associated mathematical functions > [...] > > jue > > -- http://mail.python.org/mailman/listinfo/python-list
Re: complex numbers
Operator overloading (and function overloading) helps but not enough.You have to be aware of the complex type *everywhere* you go and that's very annoying and error prone. I've been the works with C++, and later with Modelica. I am very happy that Python included *native* complex number support. I really like Python's notion of having just one data type: the duck. "Anno Siegel" <[EMAIL PROTECTED]> wrote in message news:cs145l$8d6 > > Like this? > > use Math::Complex; > > my $z = sqrt( -1); > print 1 + $z, "\n"; # prints "1+i" > > Operator overloading makes it possible to work with complex numbers as if > they were a native data type. > > Anno > -- http://mail.python.org/mailman/listinfo/python-list
Re: complex numbers
"Big and Blue" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > > > I am very happy that Python included *native* complex number > > support. > > And I have always been happy that FORTRAN supports them. > > > I really like Python's notion of having just one data type: the duck. > > So have you considered using Python for your problem? > Yes, over the holiday, I wrote a somewhat complex program using Python - just so I can apply what I have learned so far. It's a joy to use. I was able to finished the program in a fraction of the time it used to take me in Fortran (and later C). -- http://mail.python.org/mailman/listinfo/python-list
Re: complex numbers
You are focusing on computational type applications of complex numbers. For those, you can do it with any languages - including machine language. It's just a matter of how much headache you want. For instance, when constructing "software lego parts" (such as the Matlab/Simulink type), it's very annoying that you need to know what kind of signal comes in and goes out. In Malab/Simulink, for instance, you specify that the signal is of the "inherit" type (meaning you don't care what type it is - just process it). In Python, it's of type "duck", just pass it on...I don't need to care if it's real or complex. I don't need to devise yet another overloaded operator or function whenever I encounter a situation where the native language doesn't handle. "Anno Siegel" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > What kind of awareness do you mean? > > There are some operations (as comparison) that work for reals, but not > for complex numbers. If you want your program to run with complex input, > you have to avoid such operations, whether the data type is native or not. > > What other considerations are there? A typical numeric program should > just run and give complex output when fed complex input. I made the > experiment with the Perl module Statistics::Descriptive, which was > certainly written without concern for complex input, and it works without > a hitch. I'm not sure if the (complex) variance of several complex > numbers is a reasonably interpretable quantity, but I'm certain the > maths is done right. What else do you want? > > Anno -- http://mail.python.org/mailman/listinfo/python-list
Re: complex numbers
"Robert Kern" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> That's *it*.
So, how would you overload an operator to do:
With native complex support:
def twice(a):
return 2*a
print twice(3+4j), twice(2), twice("abc")
Let's presume for a moment that complex is *not* a native data type in
Python. How would we implement the above - cleanly?
--
http://mail.python.org/mailman/listinfo/python-list
Re: complex numbers
Precisely. One have to convert complex number into vectors, and vector of
complex numbers into vector of vectors, list of complex numbers into list of
vectors, , you get the idea.
And my code no longer look like the equation I have on paper...
Like I said, I've travelled down that path before with C++ and Modelica.
It gets ugly.
Anyway.
"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Op 2005-01-12, It's me schreef <[EMAIL PROTECTED]>:
> >
> > "Robert Kern" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> >>
> >> That's *it*.
> >
> > So, how would you overload an operator to do:
> >
> > With native complex support:
> >
> > def twice(a):
> > return 2*a
> >
> > print twice(3+4j), twice(2), twice("abc")
> >
> > Let's presume for a moment that complex is *not* a native data type in
> > Python. How would we implement the above - cleanly?
>
>
> I suppose in the same way as (graphic) points and vectors can be
> implemented cleanly.
>
> A few years back I had written a Vector class in python, just
> to get an understanding of how things worked. It worked without
> a problem with your twice function.
>
>
> >>> Vec(1.0,2.0)
> Vector[1.0, 2.0]
> >>> def twice(a):
> ... return 2 * a
> ...
> >>> twice(Vec(1.0,2.0))
> Vector[2.0, 4.0]
> >>>
>
>
> I suppose what can be done with a vector class could have been
> done with a complex class should complex numbers not have been
> native to python.
>
> --
> Antoon Pardon
--
http://mail.python.org/mailman/listinfo/python-list
Why would I get a TypeEror?
For this code snip: a=3 b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
counting items
Okay, I give up. What's the best way to count number of items in a list? For instance, a=[[1,2,4],4,5,[2,3]] I want to know how many items are there in a (answer should be 7 - I don't want it to be 4) I tried: b=len([x for y in a for x in y]) That doesn't work because you would get an iteration over non-sequence. I tried: g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))] b=sum(lambda(x) for x in a) and that didn't work because I get a TypeError from the len function (don't know why) I can, of course: i=0 for x in a: if isinstance(x,(list,tuple,dict)): i += len(x) else: i += 1 but that's so C-like... Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration over two sequences
I tried this and I got: [(1, 'a'), (2, 'b'), (3, 'c')] But if I change: a=[1,2] I got: [(1, 'c')] Why is that? I thought I should be getting: [(1, 'a'),(2,'b')] ? "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > zip or izip is your friend: > > import itertools > > a = [1,2,3] > b = ['a', 'b', 'c'] > > for a,b in itertools.izip(a, b): > print a, b > > -- > Regards, > > Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why would I get a TypeEror?
Sorry if my question was a little "lazy" and yes, I was asking about the "lazy evaluation". :=) I am surprised about this (and this can be dangerous, I guess). If this is true, I would run into trouble real quick if I do a: (1/x,1.0e99)[x==0] and that's not good. Something to keep in mind. :-( "harold fellermann" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > On 12.01.2005, at 18:35, It's me wrote: > > > For this code snip: > > > > a=3 > > > > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > > > Why would I get a TypeError from the len function? > > the problem is, that (1,len(a)) is evaluated, neither what type a > actually has > (python has no builtin lazy evaluation like ML). You have to do it this > way > instead: > > a=3 > ... > b = isinstance(a,(list,tuple,dict)) and len(a) or 1 > > - harold - > > -- > The opposite of a correct statement is a false statement. > But the opposite of a profound truth may be another profound truth. > -- Niels Bohr > -- http://mail.python.org/mailman/listinfo/python-list
Re: counting items
Oh, darn. I asked this kind of question before.
Somebody posted an answer before:
def flatten(seq):
for x in seq:
if hasattr(x, "__iter__"):
for subx in flatten(x):
yield subx
else:
yield x
data = [[1,5,2],8,4]
val_to_pos = {}
for i, x in enumerate(flatten(data)):
val_to_pos[x] = i + 1
print val_to_pos
"It's me" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Okay, I give up.
>
> What's the best way to count number of items in a list?
>
> For instance,
>
> a=[[1,2,4],4,5,[2,3]]
>
> I want to know how many items are there in a (answer should be 7 - I don't
> want it to be 4)
>
> I tried:
>
> b=len([x for y in a for x in y])
>
> That doesn't work because you would get an iteration over non-sequence.
>
> I tried:
>
> g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))]
> b=sum(lambda(x) for x in a)
>
> and that didn't work because I get a TypeError from the len function
(don't
> know why)
>
> I can, of course:
>
> i=0
> for x in a:
> if isinstance(x,(list,tuple,dict)):
> i += len(x)
> else:
> i += 1
>
> but that's so C-like...
>
> Thanks,
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: counting items
Yes, Mark, I came up with almost the same code (after reading back old answers from this list): def flatten(seq): for x in seq: if hasattr(x, "__iter__"): for subx in flatten(x): yield subx else: yield x def count_item(data): return len([(i,x) for i, x in enumerate(flatten(data))]) data = [[1,5,2],8,4] print count_item(data) Thanks everybody. "Mark McEahern" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > >Okay, I give up. > > > >What's the best way to count number of items in a list [that may contain lists]? > > > > > a = [[1,2,4],4,5,[2,3]] > > def iterall(seq): > for item in seq: > try: > for subitem in iterall(item): > yield subitem > except TypeError: > yield item > > all = [x for x in iterall(a)] > print len(all) > -- http://mail.python.org/mailman/listinfo/python-list
Re: counting items
Thanks. May be flatten should be build into the language somehow "Paul McGuire" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "It's me" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > Okay, I give up. > > > > What's the best way to count number of items in a list? > > > > For instance, > > > > a=[[1,2,4],4,5,[2,3]] > > > > I want to know how many items are there in a (answer should be 7 - I don't > > want it to be 4) > > > > > I've sure seen a lot of questions about the flattening of lists. I found > this version of flatten somewhere, I thought I got it from the Python > Cookbook but I can't find it now. Perhaps it was posted here on c.l.py. I > *don't* claim authorship, I'm merely an admirer of such a clean-looking > solution. > > def flatten(a): > if not isinstance(a, (tuple,list)): return [a] > if len(a)==0: return [] > return flatten(a[0])+flatten(a[1:]) > > a = [[1, 2, 4], 4, 5, [2, 3], 6, [6], [], 'askjdf'] > > print len(flatten(a)) > > gives the value 10. > > Considering how often this comes up, might there be a place for some sort of > flatten() routine in the std dist, perhaps itertools? > > -- Paul > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Why would I get a TypeEror?
Say again??? "Reinhold Birkenfeld" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > Sorry if my question was a little "lazy" and yes, I was asking about the > > "lazy evaluation". :=) > > > > I am surprised about this (and this can be dangerous, I guess). > > > > If this is true, I would run into trouble real quick if I do a: > > > > (1/x,1.0e99)[x==0] > > > > and that's not good. > > > > Something to keep in mind. :-( > > Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! > > Reinhold -- http://mail.python.org/mailman/listinfo/python-list
problem with PythonCard -> wxPython -> _core.py -> class point -> __getitem__
I've built a Python application using PythonCard 1.9 and Python 2.3 running under Windows XP. Everything works except that when I use the keyboard instead of the mouse to do certain operations in a data entry field (like Shift-Home), the program stops at line 1014 of wx-2.5.3-msw.ansi\wx\_core.py. def __getitem__(self, index): try: x = self.Get()[index] except IndexError: raise IndexError, "tuple index %d out of range of %d" %(index,len(self.Get())) return x I downloaded the current version of wxPython (2.5.3.1) and tried again. Same problem except that they've removed the exception handler and simply go with: def __getitem__(self, index):return self.Get()[index] at line 1012. The debugging shows that someone is calling this routine repeatedly with index greater then the left of self.Get(). That's the best I can do. Any help? (I can report to the wxPython list if nobody knows how to get around this) Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonCard and Py2Exe
It's:
from PythonCard.components import radiogroup
not just:
from PythonCard import radiogroup
"PipedreamerGrey" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I'm trying to create a standalone version (.exe) of PythonCard's Custdb
> sample using Py2Exe version 0.5.0. Everytime I attempt to compile the
> program, I get an error during compilation. This is the exact code I'm
> using in the setup file:
>
> from distutils.core import setup
> import py2exe
> setup( name = "custdb",
>console = ["custdb.py"],
>data_files = [ (".", ["custdb.ini", "custdb.de.rsrc.py",
> "custdb.rsrc.py", "customerdata.csv"]) ]
>)
>
> This is the error message I get when I run custdb.exe:
>
> Traceback (most recent call last):
> File "custdb.py", line 202, in ?
> app = model.Application(CustDbStack)
> File "PythonCard\model.pyc", line 337, in __init__
> File "PythonCard\resource.pyc", line 48, in getResource
> File "PythonCard\resource.pyc", line 86, in __init__
> File "PythonCard\resource.pyc", line 91, in __init__
> File "PythonCard\resource.pyc", line 91, in __init__
> File "PythonCard\resource.pyc", line 96, in __init__
> File "PythonCard\resource.pyc", line 139, in enforceSpec
> File "PythonCard\resource.pyc", line 30, in loadComponentModule
> ImportError: cannot import module 'radiogroup
>
> When I add "radiogroup" to the imports at the top of custdb.py, I get
> this error message:
>
> Traceback (most recent call last):
> File "custdb.py", line 18, in ?
> ImportError: cannot import name radiogroup
>
> This is line 18 in Custdb.py: from PythonCard import dialog, model,
> radiogroup
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Pythoncard - Mistake in walkthrough?
As stated in the on-line WalkThrough, the information there was written for an older version of the program. "Deltones" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi all, > > I'm just getting into Python/wxPython/Pythoncard and I'm trying the > tutorial from this page: > http://pythoncard.sourceforge.net/walkthrough1.html > > Is it me who's totally dense or there's some sort of confusion with > this tutorial? > > Here's what is said in the tutorial: > > Open the file starter1.py in your Python-aware editor of choice. The > Python script is, as you'd expect, brief and to the point. Here's the > important part to focus on: > > def on_menuFileExit_select(self, event): > pass > > > But here's the starter1.py code: > > #!/usr/bin/python > > from PythonCard import model > > class Minimal(model.Background): > pass > > if __name__ == '__main__': > app = model.Application(Minimal) > app.MainLoop() > > > As you can see, the on_menu line is not in the starter1.py original > script, so I guessed that it should be a part of the Minimal class. > > Then the tutorial ask me to replace the on_menu "pass" line with: > > result = dialog.alertDialog(self, 'It works!', 'Showing Off') > > but when you run the script, it runs, but clicking on Exit does not > display any dialog box. I did change the import line to include > dialog. > > Is there something I'm not seeing here or there is really a mistake > with the walkthrough? > > Thanks > > Denis -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythoncard - Mistake in walkthrough?
No, those are old still. "Deltones" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > As stated in the on-line WalkThrough, the information there was written for > > an older version of the program. > > > > > Hi, > > I understand, but the walkthrough I'm doing comes from the doc folder > of the latest windows package. I thought that the walkthrough were > updated to fit the newest version. Thanks though. > > Denis -- http://mail.python.org/mailman/listinfo/python-list
Newbie getting confused again
If I have: a = (1,2,3) how do I ended up with: res=[(1), (2), (3), (4), (5)] without doing: res=[(a[0]), (a[1]), (a[2]), (4), (5)] ??? ps: This is just a nobrainer example of what my real code is trying to do. "a" might have many many elements. That's why the explicit indexing method won't work. Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie getting confused again
*bonk, bonk, bonk* Now I feel better. Thanks, everybody. The "+" is indeed what I was looking for.It just didn't occur to me that this is the way you concatenate two lists together. But of course, that makes sense, doesn't it? Thanks again. "Peter Hansen" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > If I have: > > > > a = (1,2,3) > > Note that this is a tuple. > > > how do I ended up with: > > > > res=[(1), (2), (3), (4), (5)] > > Not that this is a list. The two aren't the same thing. > If you don't understand the difference, you might want > to review the tutorial or head over to the tutor list. > > Also note that (1) is just the same as 1, so what you > show above is the same as res=[1, 2, 3, 4, 5]. Is that > what you wanted? > > > without doing: > > > > res=[(a[0]), (a[1]), (a[2]), (4), (5)] > > Presumably what you are asking is how you can create > a new list (or tuple?) based on the contents of the > original tuple "a" but with two more elements added? > > This will do precisely what you've described, though > it does convert "a" from a tuple into a list because > you couldn't concatenate (join together) the two objects > otherwise: > > res = list(a) + [4, 5] > > > -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie getting confused again
Thanks, got it. "M.E.Farmer" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > If I have: > > > > a = (1,2,3) > > > > how do I ended up with: > > > > res=[(1), (2), (3), (4), (5)] > > > > without doing: > > > > res=[(a[0]), (a[1]), (a[2]), (4), (5)] > > > > ??? > > > > ps: This is just a nobrainer example of what my real code is trying > to do. > > "a" might have many many elements. That's why the explicit indexing > method > > won't work. > > > > Thanks, > Hello, > List objects have a method called extend(). > It is made for this. > Py> a = [1,2,3] > Py> b = [4,5,6] > Py> a.extend(b) > Py> a > [1, 2, 3, 4, 5, 6] > Since you are a newbie I also suggest you look at > your objects a little and see what they have available. > > Py>dir(a) > ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', > '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', > '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', > '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', > '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', > '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', > 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', > 'sort'] > > Then you can try and get some help from Python. > Py>help(a.extend) > Help on built-in function extend: > > extend(...) > L.extend(iterable) -- extend list by appending elements from the > iterable > > And finally use pydoc it is very helpful. > Cl> python pydoc -g > hth, > M.E.Farmer > -- http://mail.python.org/mailman/listinfo/python-list
How do I do this? (eval() on the left hand side)
I am new to the Python language. How do I do something like this: I know that a = 3 y = "a" print eval(y) would give me a print out of 3 - but how do I do something to the effect of: eval(y) = 4# hopefully the value of a gets changed to 4 ?? Thanks, -- It's me -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
"Caleb Hattingh" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi It's me > > > > > a = 3 > > y = "a" > > print eval(y) > > > > To get 'a' to be 4 here, you would say > > a = 4 > Obviously but that's not what I wish to do. > I am not sure why you would want to do otherwise? Perhaps you could > sketch out a little more about what you are trying to do? That would help > a lot. Are you aiming for something like pointer emulation with simple > datatypes? > In REXX, for instance, one can do a: interpret y' = 4' Since y contains a, then the above statement amongs to: a = 4 There are many situations where this is useful. For instance, you might be getting an input which is a string representing the name of a variable and you wish to evaluate the expression (like a calculator application, for instance). > Thanks > Caleb -- http://mail.python.org/mailman/listinfo/python-list
sys.stdin.read question
Why do I get an "AttributeError: read" message when I do: import sys r=sys.stdin.read() ?? I've tried: r=sys.stdin.read(80) r=sys.stdin.read(1) same error message. I couldn't find any reference to this function in my Python book (they have the stdout but not in). Some sample code I saw uses this function in the same manner I am and so I am assuming this is the correct syntax? Or is this a bug in Python 2.4? -- It's me -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Yes, Russell, what you suggested works. I have to chew more on the syntax to see how this is working. because in the book that I have, it says: exec code [ in globaldict [, localdict] ] ... -- It's me "Russell Blau" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "It's me" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > > > In REXX, for instance, one can do a: > > > > interpret y' = 4' > > > > Since y contains a, then the above statement amongs to: > > > > a = 4 > > > > There are many situations where this is useful. For instance, you might > be > > getting an input which is a string representing the name of a variable and > > you wish to evaluate the expression (like a calculator application, for > > instance). > > In Python, the canonical advice for this situation is, "Use a dictionary." > This has a number of advantages, including keeping your user's namespace > separate from your application's namespace. Plus it's easier to debug and > maintain the code. > > But, if you absolutely, positively have to refer to your variable > indirectly, you could do: > > exec "%s = 4" % y > > If y refers to the string "a", this will cause the variable a to refer to > the value 4. > > -- > I don't actually read my hotmail account, but you can replace hotmail with > excite if you really want to reach me. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.stdin.read question
"Grant Edwards" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On 2004-12-07, It's me <[EMAIL PROTECTED]> wrote: > > Why do I get an "AttributeError: read" message when I do: > > > > import sys > > r=sys.stdin.read() > > Dunno. Works fine for me under 2.3.4, and according to the > docs, should work under 2.4. > > What do you get when you do this: > > import sys Done that. > type(sys.stdin) I get: > dir(sys.stdin) I get: ['_RPCProxy__attributes', '_RPCProxy__getattributes', '_RPCProxy__getmethods', '_RPCProxy__methods', '__doc__', '__getattr__', '__init__', '__module__', 'encoding', 'oid', 'sockio'] > > > Some sample code I saw uses this function in the same manner I > > am and so I am assuming this is the correct syntax? > > Should be. > > > Or is this a bug in Python 2.4? > > That would be a little hard to believe. > Well, here's a copy from the Python Shell output: >>> print sys.stdin.read(5) Traceback (most recent call last): File "", line 1, in -toplevel- print sys.stdin.read(5) AttributeError: read >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I do this? (eval() on the left hand side)
Thanks for all the replies and yes I realize the associated issue of doing something like this. For simplicity sake, let's say I need to do something like this (for whatever reason): In situations like this, I wouldn't know the name of the variable in Python I need to use ahead of time and so I would have to somehow convert a string to be used as variable. Of course, I can create a dictionary to keep track of which variable has what name and this method of using exec should be avoid if at all possible. I am just trying to understand the language and see what it can do. -- It's me "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > How do I do something like this: > > > > I know that > > > > a = 3 > > y = "a" > > print eval(y) > > > > would give me a print out of 3 - but how do I do something to the effect of: > > > > eval(y) = 4# hopefully the value of a gets changed to 4 > > Generally, if you find yourself doing this, you may want to rethink your > program organization. That being said, if you are in the global scope, > one option looks something like: > > >>> a = 3 > >>> y = 'a' > >>> globals()[y] = 4 > >>> a > 4 > > If you can give us some more context on why you want to do this, we can > probably suggest a better approach. There aren't too many places where > even advanced Python programmers need to use eval... > > Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.stdin.read question
Yes, if I run the script from the command prompt, it works. I was running it inside the Python IDE. Thanks, -- It's me "Grant Edwards" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On 2004-12-07, It's me <[EMAIL PROTECTED]> wrote: > > >> Dunno. Works fine for me under 2.3.4, and according to the > >> docs, should work under 2.4. > >> > >> What do you get when you do this: > >> > >> import sys > > > > Done that. > > > >> type(sys.stdin) > > > > I get: > > > > > > > >> dir(sys.stdin) > > > > I get: > > > > ['_RPCProxy__attributes', '_RPCProxy__getattributes', > > '_RPCProxy__getmethods', '_RPCProxy__methods', '__doc__', '__getattr__', > > '__init__', '__module__', 'encoding', 'oid', 'sockio'] > > > > > As somebody else already suggested, you must be running your > program inside some sort of IDE that replaces sys.stdin with > some other object that doesn't have a read() method. Try > running the program from a shell prompt. > > > -- > Grant Edwards grante Yow! Someone in DAYTON, > at Ohio is selling USED >visi.comCARPETS to a SERBO-CROATIAN -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.3.5 ?
Not to mention that there are packages out there that doesn't work (yet) with 2.4. Pynum is one such package. -- It's me "Larry Bates" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Just because 2.4 arrives doesn't mean that ALL work is stopped > on 2.3. It is quite common to have releases overlap. The very > newest release is put out (2.4) , but bugs are still being fixed > in older (2.3). > > Larry Bates > > > > Luis M. Gonzalez wrote: > > I'm confussed... > > Python 2.4 (final) hs been released a few days ago, but now I see that > > Python 2.3.5 is being worked on. > > Why? What does it mean? > > -- http://mail.python.org/mailman/listinfo/python-list
swig & Python question
I am playing around with SWING building a Python module using the no brainer
example in http://www.swig.org/tutorial.html. With that first example,
/* File : example.c */
#include
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(<ime);
return ctime(<ime);
}
and using the swig file of:
/* example.i */
%module example
%{
/* Put header files here (optional) */
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
I was able to execute this Python script:
>>> import example
>>> example.fact(5)
120
>>> example.my_mod(7,3)
1
>>> example.get_time()
'Sun Feb 11 23:01:07 1996'
>>>
However, when I try to access the gloabl variable My_variable by doing:
print example.cvar
I get a blank (rather then a value of 3.0).
Why?
--
It's me
--
http://mail.python.org/mailman/listinfo/python-list
Re: swig & Python question
"It's me" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I am playing around with SWING building a Python module using the no brainer > example in http://www.swig.org/tutorial.html. With that first example, > Oops! Soapy fingers. "SWIG" - not "SWING". -- It's me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a C program from a Python Script
I would expect C to run circles around the same operation under Python. As a general rule of thumb, you should use C for time cirtical operations (computer time, that is), and use Python for human time critical situations (you can get a program developed much faster). I just discovered a magical package call SWIG (http://www.swig.org) that makes writing C wrappers for Python always a child's play. It's incredible! Where were these guys years ago when I had to pay somebody moocho money to develop a script language wrapper for my application!!! -- It's me "Brad Tilley" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Grant Edwards wrote: > > Huh? What do you mean "write a file open"? You want to read a > > C source file and execute the C source? If you have access to > > a C interpreter, I guess you could invoke the interpreter from > > python using popen, and feed the C source to it. Alternatively > > you could invoke a compiler and linker from C to generate an > > executable and then execute the resulting file. > > > > > >>for root, files, dirs in os.walk(path) > >> for f in files: > >> try: > >> EXECUTE_C_PROGRAM > > > > > > You're going to have to explain clearly what you mean by > > "EXECUTE_C_PROGRAM". If you want to, you can certainly run a > > binary executable that was generated from C source, (e.g. an > > ELF file under Linux or whatever a .exe file is under Windows). > > Appears I was finger-tied. I meant "a C program that opens and reads > files" while Python does everything else. How does one integrate C into > a Python script like that? > > So, instead of this: > > for root, files, dirs in os.walk(path) > for f in files: > try: > x = file(f, 'rb') > data = x.read() > x.close() > this: > > for root, files, dirs in os.walk(path) > for f in files: > try: > EXECUTE_C_PROGRAM > > From the Simpsons: > Frink: "Here we have an ordinary square." > Wiggum: "Whoa! Slow down egghead!" -- http://mail.python.org/mailman/listinfo/python-list
Re: New versions breaking extensions, etc.
On the other hand, it can be annoying. I can't use Python 2.4 right now because NumPy won't run. So, I need to wait for NumPy to get updated. Of course, one would say: but NumPy is open source, go build it yourself. My answer is simple: If there are more then 24 hours to a day, I definitely would... -- It's me "John Machin" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Jive wrote: > "Martin v. Löwis" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > OTOH, people who only have VC6 just need to buy VS.NET 2003, > > which is still available. > > I don't even know how to do that! :-) What's the difference between VC++ > .net Standard and Visual Studio .net Pro? (Besides $370?) Is the former > C++ only, but with the IDE, and the later the whole shebang with SourceSafe, > VBASIC, and all that? > > OH NO! I've gone seriously off-topic. Please don't call the Spanish > Inquisiton. Allow me to re-phrase the question: What do I need to build > (on-topic) Python extensions? Short answer to Jive's question: (1) free non-MS C compiler (either MinGW or Borland) (2) inner calm. I really can't understand what all the screaming and yelling is about. Windows Python is built using an MS compiler. Those extension developers who can't/won't buy the MS compiler use either the free MinGW compiler or the free Borland 5.5 compiler (or both!). Yes, you have to be careful about mixing the runtimes. An extension that tries to use a FILE * that was created by Python will crash. Using free() on a pointer that was malloc()ed by the other party isn't a bright idea either. There are adequate solutions to these problems, involving Python-supplied higher-level functions instead of C runtime functions. Otherwise, not a problem. Distutils has made the process of using MinGW and bcpp a snap. The documentation is adequate. When a new version of Python comes out, one rebuilds and tests one's extensions. So ... now there are THREE compilers that can be used instead of the one that Python's built with; what's the big deal? -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonWin Not Updating
It works fine here. -- It's me "Chris" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I'm working on a program in PythonWin. The problem I'm running into is > that after I make a code change, PythonWin doesn't always see it. Has > anyone else had this problem? > > Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
"Adam DePrince" <[EMAIL PROTECTED]> wrote in message > > Don't do it, unless your goal is simply to embarrass and insult > programmers. > I saw this code from an earlier post: lst1 = ["ab", "ac", "ba", "bb", "bc"] lst2 = ["ac", "ab", "bd", "cb", "bb"] dct1 = dict.fromkeys(lst1) print [x for x in lst1 if x not in dct1] print [x for x in lst1 if x in dct1] It's simply remarkable for somebody to be able to do it so cleanly (and so obviously) - "out of the box", if you may. Sure, you can do it in Basic. Ur...sure? Yes, sure... > > > Adam DePrince > > -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
"Gregor Horvath" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Peter Otten wrote: > > > May you could give us an idea of the current state of basic affairs then by > > translating the following example snippet: > > yes you can do it in VB6, but pythons lists and dictionarys are superior > to those built in in VB and I think to those in most other languages. > > > > > It's me wrote: > > > > > >>I saw this code from an earlier post: > >> > >>lst1 = ["ab", "ac", "ba", "bb", "bc"] > >>lst2 = ["ac", "ab", "bd", "cb", "bb"] > >>dct1 = dict.fromkeys(lst1) > >>print [x for x in lst1 if x not in dct1] > >>print [x for x in lst1 if x in dct1] > > I think line3 should be > > >>dct1 = dict.fromkeys(lst2) > > correct? > Correct. > VB6 Code: > > Sub xy() > > Dim lst1 As New Collection > Dim lst2 As New Collection > > lst1.Add "ab", "ab": lst1.Add "ac", "ac": lst1.Add "ba", "ba": lst1.Add > "bb", "bb": lst1.Add "bc", "bc" > lst2.Add "ac", "ac": lst2.Add "ab", "ab": lst2.Add "bd", "bd": lst2.Add > "cb", "cb": lst2.Add "bb", "bb" > > For Each item In lst1 >If ColHasKey(lst2, item) Then Debug.Print "in:" & item > Next > > For Each item In lst1 >If Not ColHasKey(lst2, item) Then Debug.Print "not in:" & item > Next > > End Sub > > > Function ColHasKey(col As Collection, item) As Boolean > On Error GoTo er >A = col(item) >ColHasKey = True > Exit Function > er: >If Err.Number = 5 Then > ColHasKey = False >Else > Err.Raise Err.Number >End If > End Function Absolutely *ugly*! But still, your point is well taken. Thank you for pointing this out. Adam was right: "Don't do it, unless your goal is simply to embarrass and insult programmers". -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
"Gregor Horvath" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > Absolutely *ugly*! > > > > But still, your point is well taken. Thank you for pointing this out. > > > > Adam was right: > > > > "Don't do it, unless your goal is simply to embarrass and insult > > programmers". > > > OK. Then please schow me, how you can create a complex form with grids, > explorer like trees etc. in 2 minutes in standard python. > > Or make any given standard python object accessible from MS Excel in 2 > minutes. > > -- > Greg I thought we are talking about the language, are we not? -- It's me -- http://mail.python.org/mailman/listinfo/python-list
PyCrust: What am I suppose to do?
I am trying out PyCrust and at a lost what to do next. With the previous IDE I tried, the IDE pops up the console and the editor. From the editor, I can set up breakpoints and debug and so forth. Yes, I can even run the script. With PyCrust, the nice looking 3-pane window pops up with lots of tabs...a prompt...and then??? Where is the file I am trying to run? Even the File options are all greyed out... -- http://mail.python.org/mailman/listinfo/python-list
Re: swig & Python question
Whether SWIG will work in a "no brainer" way or not depends on the original code, I think. If the original code uses a very convoluted design, of course things will get hairy. If the package uses a very clean structure, I think you will find SWIG works out very nicely. The intriguing things is, however, once you structure the package to a form SWIG would work, it opens up the door to support multiple script languages (and they have a long list of supported script languages). If you hand crafted it to run the Python-C API, then you can only use Python as script. -- It's me "Keith Dart" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's me wrote: > > "It's me" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > > > >>I am playing around with SWING building a Python module using the no > > > > brainer > > > >>example in http://www.swig.org/tutorial.html. With that first example, > >> > > > > > > Oops! Soapy fingers. "SWIG" - not "SWING". > > > > -- > > It's me. > > I have used SWIG before, and it's not always such a "no-brainer". In > fact, it rarely is except for trivial examples. But it can work. I think > it is best suited for wrapping large libraries. For small stuff, it > would be better to just do it "manually" using the Python C API. > > > Good luck. > > -- > It's not me. > > > > > -- > \/ \/ > (O O) > -- oOOo~(_)~oOOo-- -- > Keith Dart <[EMAIL PROTECTED]> > public key: ID: F3D288E4 > -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
"abisofile" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > hi > > I'm new to programming.I've try a little BASIC so I want ask since > Python is also interpreted lang if it's similar to BASIC. > > > Is a Ferrari similar to a horse-wagon? Yes, they both have 4 wheels. :=) -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
"Jan Dries" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Michael Hoffman wrote:
> > Gregor Horvath wrote:
> >
> > > Or make any given standard python object accessible from MS Excel in
2
> > > minutes.
> >
> > from win32com.client import Dispatch
> >
> > xlApp = Dispatch("Excel.Application")
> > xlApp.Visible = 1
> > xlApp.Workbooks.Add()
> > xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
> > xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
> > xlApp.ActiveWorkbook.Close(SaveChanges=0)
> > xlApp.Quit()
> > del xlApp
> >
> > (stolen from )
>
> Nice, but not really what the OP asked for.
What the OP asked for isn't what was discussed neither.
> You make Excel accessible
> from Python, instead of the other way round.
>
Again, that's a political issue - not technical nor language related.
Monopolictic empire has their way of doing things and as IT slaves, we have
to obey what the master BG wants us to do.
Anyway, here's another piece I find very nice:
http://starship.python.net/crew/pirx/spam7/COMtut.PPT
--
http://mail.python.org/mailman/listinfo/python-list
