Newby: how to transform text into lines of text
Hello,
I'va read a text file into variable "a"
a=open('FicheroTexto.txt','r')
a.read()
"a" contains all the lines of the text separated by '\n' characters.
Now, I want to work with each line separately, without the '\n'
character.
How can I get variable "b" as a list of such lines?
Thank you for your help
--
http://mail.python.org/mailman/listinfo/python-list
Re: Newby: how to transform text into lines of text
On 25 ene, 14:36, "Diez B. Roggisch" wrote:
> vsoler schrieb:
>
> > Hello,
>
> > I'va read a text file into variable "a"
>
> > a=open('FicheroTexto.txt','r')
> > a.read()
>
> > "a" contains all the lines of the text separated by '\n' characters.
>
> No, it doesn't. "a.read()" *returns* the contents, but you don't assign
> it, so it is discarded.
>
> > Now, I want to work with each line separately, without the '\n'
> > character.
>
> > How can I get variable "b" as a list of such lines?
>
> The idiomatic way would be iterating over the file-object itself - which
> will get you the lines:
>
> with open("foo.txt") as inf:
> for line in inf:
> print line
>
> The advantage is that this works even for large files that otherwise
> won't fit into memory. Your approach of reading the full contents can be
> used like this:
>
> content = a.read()
> for line in content.split("\n"):
> print line
>
> Diez
Thanks a lot. Very quick and clear
--
http://mail.python.org/mailman/listinfo/python-list
getting values from a text file (newby)
Hi,
My foo.txt file contains the following:
1,"house","2,5"
2,"table","6,7"
3,"chair","-4,5"
... as seen with notepad.
This file was created with the OpenOffice Calc spreadsheet, but since
I use comma as the decimal separator for numbers, the last value in
each line appears sorrounded by quotes.
I would like to obtain:
[[1,"house",2.5], [2,"table",6.7], [3,"chair",-4.5]]
in order to process the content of the file. However, so far, I have
not obtained the desired result.
I started testing with (only for first line):
f=open('foo.txt','r')
t=f.readline()
print t
t=t.split(',')
print t
f.close()
But what I am getting is far more complex than what I expected:
1,"house","2,5"
['1', '"house"', '"2', '5"\n']
which is unprocessable.
Can anyboby help?
--
http://mail.python.org/mailman/listinfo/python-list
Re: getting values from a text file (newby)
On 1 feb, 19:02, Stephen Hansen wrote:
> On Sun, Feb 1, 2009 at 9:24 AM, vsolerwrote:Hi,
> My foo.txt file contains the following:
> 1,"house","2,5"
> 2,"table","6,7"
> 3,"chair","-4,5"
> ... as seen with notepad.
> This file was created with the OpenOffice Calc spreadsheet, but since
> I use comma as the decimal separator for numbers, the last value in
> each line appears sorrounded by quotes.
> I would like to obtain:
> [[1,"house",2.5], [2,"table",6.7], [3,"chair",-4.5]]
> If I read your requirements, right, I think you want:import csv
> data = []
> reader = csv.reader(open("filename", "r"))
> for line in reader:
> data.append(
> line[0], line[1], float(line[2].replace(",", "."))
> )
> print data
> Although you may want to replace that last bit with
> decimal.Decimal(line[2].replace(",","."))
> If you want an exact result and not the approximate floating point result.
> Basically the csv module can read through the CSV file very easily, but
> because you're using commas instead of points you just have to edit that out
> before you convert it to a number.
> --S
>
> signature.asc
> < 1 KBVerDescargar
with small modifications, your answers work perfectly!!!
r: in the open statement, why do you use 'rb' as 2nd argument? b is
supposed to be binary, and my file is text!
Steve: your idea works
Stephen: I got an error message saying that append can only take one
argument while you add three; I have added [ ] around the three
arguments; now it's fine; I've also added int() around first argument
to turn it into an integer.
Thank you all indeed!
--
http://mail.python.org/mailman/listinfo/python-list
Re: getting values from a text file (newby)
On 1 feb, 23:57, John Machin wrote: > On Feb 2, 6:18 am, vsoler wrote: > > > > > r: in the open statement, why do you use 'rb' as 2nd argument? b is > > supposed to be binary, and my file is text! > > Because unlike Stephen, r has read the csv manual. Binary mode is > required to handle properly cases like '\n' embedded in a field -- > something which can easily happen when the data has been extracted > from a database with slack data-entry validation. Where can I get the csv manual? -- http://mail.python.org/mailman/listinfo/python-list
Source code for csv module
Hi you all, I just discovered the csv module here in the comp.lang.python group. I have found its manual, which is publicly available, but since I am still a newby, learning techniques, I was wondering if the source code for this module is available. Is it possible to have a look at it? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Source code for csv module
On 2 feb, 21:51, Jon Clements wrote: > On 2 Feb, 20:46, vsoler wrote: > > > Hi you all, > > > I just discovered the csv module here in the comp.lang.python group. > > > I have found its manual, which is publicly available, but since I am > > still a newby, learning techniques, I was wondering if the source code > > for this module is available. > > > Is it possible to have a look at it? > > > Thanks > > The csv module is a wrapper around a C extension. If you're happy > reading C code then downloading the Python sources will let you take a > goosey. > > Jon. I'm still interested in learning python techniques. Are there any other modules (standard or complementary) that I can use in my education? -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
On Dec 6, 11:53 pm, "Martin P. Hellwig" wrote: > Edward A. Falk wrote: > > > > > For development purposes, you should stick with the oldest version that will > > actually run your code. Every time you move to a more modern version, > > you're > > leaving potential users/customers out in the cold. > > If the fear of customers disatification prevents you from using a > certain version of X, you should consider a deployment strategy that > cuts out dependencies as much as possible. Although this will result in > a larger end package and possible high amount of duplication, it is > still preferable to just stop supporting popular platforms or be swamped > away with bugs due to version mismatches. > > -- > MPHhttp://blog.dcuktec.com > 'If consumed, best digested with added seasoning to own preference.' Your posts have been very enlightening. Thank you very much!!! -- http://mail.python.org/mailman/listinfo/python-list
Where is my namespace?
I take the example from Mark Lutz's excellent book "Learning Python". *** In nested1.py I have: X=99 def printer(): print X *** In nested2.py I have: from nested1 import X, printer X=88 printer() What is amazing is that running nested2.py prints 99 and not 88. My questions are: 1. Using statement "from" instead of "import" should not create a namespace, at least that's what I think. However, the printer() function is able to find 99 which is residing in... a namespace? 2. I have tried to access the 88 by qualification from nested2.py. However, I cannot. If using "print nested1.X" in nested2.py I get an error 3. Mark says: The from statement is really an assignment to names in the importer's scope--a name-copy operation, not a name aliasing. I don't fully understand what he means. Could anybody explain? Thank you very much for your time. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is my namespace?
On Dec 7, 5:39 pm, Benjamin Kaplan wrote: > On Mon, Dec 7, 2009 at 11:10 AM, vsoler wrote: > > I take the example from Mark Lutz's excellent book "Learning Python". > > > *** In nested1.py I have: > > X=99 > > def printer(): print X > > > *** In nested2.py I have: > > from nested1 import X, printer > > X=88 > > printer() > > > What is amazing is that running nested2.py prints 99 and not 88. > > > My questions are: > > > 1. Using statement "from" instead of "import" should not create a > > namespace, at least that's what I think. However, the printer() > > function is able to find 99 which is residing in... a namespace? > > It doesn't create a namespace. But printer is still in nested1. When > you do a "from ... import ...", the objects are imported into the > current namespace. However, they are different names for what is > currently the same object. They still follow Python's object > semantics. Here's a simplified overview of what happens > > you run nested2.py > > 1 namespace: nested2, nothing in it (except for the special stuff) > > you run "from nested1 import X, printer". This executes everything in > nested1 (because def and class are just executable statements in > Python) and binds X and printer in nested2 to the objects in nested1. > Note that these are now different names for the same objects. > > nested1: X = 99, printer = > nested2: X = 99 printer = > > you call X = 88. Because you are rebinding the object, this name > (nested2.X) is the only one that gets changed. Rebinding doesn't touch > the object in nested1. > > nested1: X=99, printer = > nested2: x=88 printer = > > Notice how the name "printer" in nested2 still refers to an object in > nested1. It is simply another reference, not a new object. When you > call printer, it's still sitting in nested1 and only sees nested1's X. > > > 2. I have tried to access the 88 by qualification from nested2.py. > > However, I cannot. If using "print nested1.X" in nested2.py I get an > > error > > that's because when you do "from ... import ..." it doesn't import the > module itself. There's a totally different behavior between from ... > import and import. Here's what you're trying to do > > nested2.py : > > import nested1 > > nested1.X = 88 > nested1.printer() > > > > > 3. Mark says: The from statement is really an assignment to names in > > the importer's scope--a name-copy operation, not a name aliasing. I > > don't fully understand what he means. Could anybody explain? > > Like I showed before, when you change the unqualified "X" in nested2, > the X in nested1 doesn't change. Using from import is identical to > doing something like this > > a = 1 > b = a > b = 5 > a == 1 #True > > a is a name that temporarily referred to the same object as a. > However, when you reassign b, it makes the name "b" refer to a > different object. It doesn't change the object that a and b both refer > to. When you import using from ... import, you end up with 2 > different names that, at the start refer to the same object. Mutation > (if you're using a mutable object) will show up in both namespaces, > since they are referring to the same object, but assignment does not. > > > Thank you very much for your time. > > > Vicente Soler > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I appreciate the preciseness and clearness of your explanations. Thank you very much indeed. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
unable to read the __main__ namespace
I'm learning Python, and I am very fond of it. Using Python 2.6 I am able to list all the names in a class namespace: class abc: pass abc.a1=7 abc.a2='Text' print abc.__dict__.keys() a) However, I do not know how to read the __main__ namespace print __main__.__dict__.keys()# Just does not work b) How do i read an imported module namespace? c) How could I possibly list the names and contents of the namespace of my python session? Thank you for your help. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: unable to read the __main__ namespace
On Dec 13, 12:34 pm, Chris Rebert wrote: > On Sun, Dec 13, 2009 at 3:20 AM, vsoler wrote: > > I'm learning Python, and I am very fond of it. > > > Using Python 2.6 > > > I am able to list all the names in a class namespace: > > > class abc: pass > > abc.a1=7 > > abc.a2='Text' > > > print abc.__dict__.keys() > > That is more simply written as: > > print dir(abc) > > > a) However, I do not know how to read the __main__ namespace > > > print __main__.__dict__.keys() # Just does not work > > __main__ is not used or set and has no special meaning to the Python > interpreter. It's true that __name__ == "__main__" in the body of the > main module, but you can't actually access it by that name. > > > b) How do i read an imported module namespace? > > import module > print dir(module) > > > c) How could I possibly list the names and contents of the namespace > > of my python session? > > print dir() > > I'd advise reading the docs on > it:http://docs.python.org/library/functions.html#dir > > Cheers, > Chris > --http://blog.rebertia.com Thank you very much. I now know how to proceed -- http://mail.python.org/mailman/listinfo/python-list
Default working directory
I'm using Python 2.6.4 on Windows (Vista & 7) I usually start Python by clicking on Start Menu the Python IDLE (Python GUI). However, if I want to save a new source *.py file, the default directory proposed for saving is not the one that I want. What can I do if I want that the change of default directory permanently, that is, if I quit python and I reenter it, the default is still the one I have chosen? Thank you for your help. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Default working directory
On 22 dic, 18:22, "Gabriel Genellina" wrote: > En Tue, 22 Dec 2009 14:04:23 -0300, vsoler > escribió: > > > I'm using Python 2.6.4 on Windows (Vista & 7) > > > I usually start Python by clicking on Start Menu the Python IDLE > > (Python GUI). > > > However, if I want to save a new source *.py file, the default > > directory proposed for saving is not the one that I want. > > > What can I do if I want that the change of default directory > > permanently, that is, if I quit python and I reenter it, the default > > is still the one I have chosen? > > Right click on the IDLE shortcut in the Start menu (or create a new > shortcut on your desktop), choose Properties, and set the Startup > Directory to your preferred directory. > > -- > Gabriel Genellina I'll try it! Thank you -- http://mail.python.org/mailman/listinfo/python-list
Endless loop
hello, I'm learning Python and OOP, and I am confronted with a rather theoretical problem. If I run the following script: class stepper: def __getitem__(self, i): return self.data[i] X=stepper() X.data="Spam" for item in X: print item, ... what I get is S p a m which seems logical to me since the loop stops after the 4th character. However if I run class stepper: def __getitem__(self, i): return i X=stepper() X.data="Spam" for item in X: print item, ... what I get is an endless loop, starting at zero:0 1 2 3 4 5 6 7 8 9 10 11 and so on. My question is: why does this second script not stop after printing number 3? what made the first one stop while the second one will not? Thanks for your advise Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Endless loop
On 2 ene, 14:21, Ulrich Eckhardt wrote: > vsoler wrote: > > class stepper: > > def __getitem__(self, i): > > return self.data[i] > > > X=stepper() > > X.data="Spam" > > for item in X: > > print item, > > > ... what I get is S p a m which seems logical to me since the > > loop stops after the 4th character. > > I think you're mistaking the cause and effect here, see below. > > > class stepper: > > def __getitem__(self, i): > > return i > > > X=stepper() > > X.data="Spam" > > for item in X: > > print item, > > > ... what I get is an endless loop, starting at zero: 0 1 2 3 4 5 6 > > 7 8 9 10 11 and so on. > > > My question is: why does this second script not stop after printing > > number 3? what made the first one stop while the second one will not? > > First thing to observe in the second case is that X's data field is not used > anywhere. The field is set and then not used any further. In particular, it > is not used to somehow get the length of the sequence to return. > > Now, "spam"[4] will raise an IndexError, thus terminating the iteration. The > second implementation which only returns the index never will do that, so > the iteration never stops. > > Uli It's clear, I now understand. Thank you -- http://mail.python.org/mailman/listinfo/python-list
What is the best data structure for a very simple spreadsheet?
Hi, Not sure this is the best group to post, but I cannot think of any other. My application would contain a limited set of "cells" represented by the instances of a Cell class: class Cell: ... A1=Cell(7) A2=Cell(2*A1) A3=Cell(3*A1+A2) A4=Cell(A3*4) Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140 Now, I somehow want to be able to show a dependency tree 1 level dependency trees A1: None A2: A1 A3: A1, A2 A4: A3 All levels dependency trees A1: None A2: A1 A3: A1, A2 A4: A3, A2, A1 Leaf + values dependency trees: A1: 7 A2: A1=7, 2 A3: 3, A1=7, 2 A4: 3, A1=7, 2, 4 What I'd like to know is: 1) what are, in your opinion, the basic elements of the Cell class? 2) Do I need a parser to evaluate the formulas like “3*A1+A2”? Can you recommend one library that already contains one? 3) Do I need a tree data structure to represent my data? would the tree be an attribute of the class instance? I imagine a lot can be said on these questions. What I am looking for is some hints that help me get out of where I am now. Any help is highly appreciated. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best data structure for a very simple spreadsheet?
On Jan 3, 1:28 pm, Steven D'Aprano wrote:
> On Sun, 03 Jan 2010 03:27:46 -0800, vsoler wrote:
> > My application would contain a limited set of "cells" represented by the
> > instances of a Cell class:
>
> > class Cell:
> > ...
>
> > A1=Cell(7)
> > A2=Cell(2*A1)
> > A3=Cell(3*A1+A2)
> > A4=Cell(A3*4)
>
> > Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140
>
> > Now, I somehow want to be able to show a dependency tree
>
> > 1 level dependency trees
> > A1: None
> > A2: A1
> > A3: A1, A2
> > A4: A3
>
> > All levels dependency trees
>
> > A1: None
> > A2: A1
> > A3: A1, A2
> > A4: A3, A2, A1
>
> > Leaf + values dependency trees:
>
> > A1: 7
> > A2: A1=7, 2
> > A3: 3, A1=7, 2
> > A4: 3, A1=7, 2, 4
>
> > What I'd like to know is:
>
> > 1) what are, in your opinion, the basic elements of the Cell class?
>
> def Cell(object):
> def __init__(self, payload):
> self.payload = payload
> def __str__(self):
> return str(self.payload)
> def __float__(self):
> return float(self.payload)
> def dependency(self):
> try:
> return self.payload.dependency()
> except AttributeError:
> return ['None']
>
> Cells can contain one of three things: a number, a string, or a formula.
> The first two can be supported by providing a built-in Python object
> (float or str) as payload. You can support formulae two ways that I can
> think of:
>
> (1) Provide a formula as a string, with a leading '='. Then, whenever you
> want to evaluate such a cell, you fetch the string from the cell, parse
> it, generate an arithmetic expression, and calculate it.
>
> (2) Instead of parsing the formula on every single spreadsheet refresh,
> use a couple of helper classes:
>
> class Indirect(object):
> def __init__(self, ref, sheet=None):
> if sheet is None:
> self.sheet = default_sheet()
> else:
> self.sheet = sheet
> self.ref = ref
> def __str__(self):
> return str(self.sheet[self.ref])
> def float(self):
> return float(self.sheet[self.ref])
> def dependency(self):
> return [self.ref]
>
> class Formula(object):
> def __init__(self, x, y, op):
> self.x = x
> self.y = y
> self.op = op
> def eval(self):
> return self.op(float(x), float(y))
> def dependency(self):
> return self.x.dependency(level) + self.y.dependency(level)
>
> Then do something like this:
>
> sheet = {}
> sheet['A1'] = Cell(7)
> sheet['A2'] = Cell(Formula(2, Indirect('A1'), operator.mul))
> sheet['A3'] = Cell(
> Formula(
> Formula(3, Indirect('A1'), operator.mul),
> Indirect('A2'),
> operator.add
> ))
> sheet['A4'] = Cell(Formula(Indirect('A3'), 4, operator.mul))
>
> Then you only need to parse each human-readable formula like '=2*A1' once.
>
> > 2) Do I need a parser to evaluate the formulas like “3*A1+A2”?
>
> Yes.
>
> > Can you recommend one library that already contains one?
>
> Try PyParsing.
>
> > 3) Do I need a tree
> > data structure to represent my data? would the tree be an attribute of
> > the class instance?
>
> I suspect a dict will be faster.
>
> To get the dependencies of each cell:
>
> for key, value in sheet.items():
> print key, value.dependency()
>
> Keep in mind I haven't tested ANY of this -- it is entirely stream of
> consciousness. I've never actually done this, so I have no idea whether
> it is a good approach or not, but it seems to me that it might be.
>
> --
> Steven
WOW!!!
After lunch I am going to read your post thoroughly, but I can already
see that you've put into it a lot of time and expertise.
Thank you
--
http://mail.python.org/mailman/listinfo/python-list
parsing an Excel formula with the re module
Hello, I am acessing an Excel file by means of Win 32 COM technology. For a given cell, I am able to read its formula. I want to make a map of how cells reference one another, how different sheets reference one another, how workbooks reference one another, etc. Hence, I need to parse Excel formulas. Can I do it by means only of re (regular expressions)? I know that for simple formulas such as "=3*A7+5" it is indeed possible. What about complex for formulas that include functions, sheet names and possibly other *.xls files? For example"=Book1!A5+8" should be parsed into ["=","Book1", "!", "A5","+","8"] Can anybody help? Any suggestions? Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing an Excel formula with the re module
On 5 ene, 19:35, MRAB wrote: > vsoler wrote: > > Hello, > > > I am acessing an Excel file by means of Win 32 COM technology. > > For a given cell, I am able to read its formula. I want to make a map > > of how cells reference one another, how different sheets reference one > > another, how workbooks reference one another, etc. > > > Hence, I need to parse Excel formulas. Can I do it by means only of re > > (regular expressions)? > > > I know that for simple formulas such as "=3*A7+5" it is indeed > > possible. What about complex for formulas that include functions, > > sheet names and possibly other *.xls files? > > > For example "=Book1!A5+8" should be parsed into ["=","Book1", "!", > > "A5","+","8"] > > > Can anybody help? Any suggestions? > > Do you mean "how" or do you really mean "whether", ie, get a list of the > other cells that are referred to by a certain cell, for example, > "=3*A7+5" should give ["A7"] and "=Book1!A5+8" should give ["Book1!A5"]? I'd like to know how to do it, should it be possible. Vicente -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best data structure for a very simple spreadsheet?
On 3 ene, 22:40, mdipierro wrote: > Perhaps this can be useful:http://www.web2py.com/examples/spreadsheet > > The code is in a single file with not dependencies and it does not > require web2py to > run:http://code.google.com/p/web2py/source/browse/gluon/contrib/spreadshe... > > Here is a sample controller that shows you how to embed the > spreadsheet in web > page:http://code.google.com/p/web2py/source/browse/applications/examples/c... > > Massimo > > On Jan 3, 5:27 am, vsoler wrote: > > > Hi, > > > Not sure this is the best group to post, but I cannot think of any > > other. > > > My application would contain a limited set of "cells" represented by > > the instances of a Cell class: > > > class Cell: > > ... > > > A1=Cell(7) > > A2=Cell(2*A1) > > A3=Cell(3*A1+A2) > > A4=Cell(A3*4) > > > Of course, A1 = 7, A2 = 14, A3 = 35 and A4 = 140 > > > Now, I somehow want to be able to show a dependency tree > > > 1 level dependency trees > > A1: None > > A2: A1 > > A3: A1, A2 > > A4: A3 > > > All levels dependency trees > > > A1: None > > A2: A1 > > A3: A1, A2 > > A4: A3, A2, A1 > > > Leaf + values dependency trees: > > > A1: 7 > > A2: A1=7, 2 > > A3: 3, A1=7, 2 > > A4: 3, A1=7, 2, 4 > > > What I'd like to know is: > > > 1) what are, in your opinion, the basic elements of the Cell class? > > 2) Do I need a parser to evaluate the formulas like “3*A1+A2”? Can you > > recommend one library that already contains one? > > 3) Do I need a tree data structure to represent my data? would the > > tree be an attribute of the class instance? > > > I imagine a lot can be said on these questions. What I am looking for > > is some hints that help me get out of where I am now. > > > Any help is highly appreciated. > > > Vicente Soler > > There is something that I appreciate in this group, and it is the high degree of knowledge of all the participants that are helping with their answers. After studying your suggestions, I'll come back to you. Thank you very much. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing an Excel formula with the re module
On 5 ene, 20:05, Mensanator wrote: > On Jan 5, 12:35 pm, MRAB wrote: > > > > > vsoler wrote: > > > Hello, > > > > I am acessing an Excel file by means of Win 32 COM technology. > > > For a given cell, I am able to read its formula. I want to make a map > > > of how cells reference one another, how different sheets reference one > > > another, how workbooks reference one another, etc. > > > > Hence, I need to parse Excel formulas. Can I do it by means only of re > > > (regular expressions)? > > > > I know that for simple formulas such as "=3*A7+5" it is indeed > > > possible. What about complex for formulas that include functions, > > > sheet names and possibly other *.xls files? > > > > For example "=Book1!A5+8" should be parsed into ["=","Book1", "!", > > > "A5","+","8"] > > > > Can anybody help? Any suggestions? > > > Do you mean "how" or do you really mean "whether", ie, get a list of the > > other cells that are referred to by a certain cell, for example, > > "=3*A7+5" should give ["A7"] and "=Book1!A5+8" should give ["Book1!A5] > > Ok, although "Book1" would be the default name of a workbook, with > default > worksheets labeled "Sheet1". "Sheet2", etc. > > If I had a worksheet named "Sheety" that wanted to reference a cell on > "Sheetx" > OF THE SAME WORKBOOK, it would be =Sheet2!A7. If the reference was to > a completely > different workbook (say Book1 with worksheets labeled "Sheet1", > "Sheet2") then > the cell might have =[Book1]Sheet1!A7. > > And don't forget the $'s! You may see =[Book1]Sheet1!$A$7. Yes, Mensanator, but... what re should I use? I'm looking for the re statement. No doubt you can help! Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing an Excel formula with the re module
On 5 ene, 20:21, vsoler wrote:
> On 5 ene, 20:05, Mensanator wrote:
>
>
>
> > On Jan 5, 12:35 pm, MRAB wrote:
>
> > > vsoler wrote:
> > > > Hello,
>
> > > > I am acessing an Excel file by means of Win 32 COM technology.
> > > > For a given cell, I am able to read its formula. I want to make a map
> > > > of how cells reference one another, how different sheets reference one
> > > > another, how workbooks reference one another, etc.
>
> > > > Hence, I need to parse Excel formulas. Can I do it by means only of re
> > > > (regular expressions)?
>
> > > > I know that for simple formulas such as "=3*A7+5" it is indeed
> > > > possible. What about complex for formulas that include functions,
> > > > sheet names and possibly other *.xls files?
>
> > > > For example "=Book1!A5+8" should be parsed into ["=","Book1", "!",
> > > > "A5","+","8"]
>
> > > > Can anybody help? Any suggestions?
>
> > > Do you mean "how" or do you really mean "whether", ie, get a list of the
> > > other cells that are referred to by a certain cell, for example,
> > > "=3*A7+5" should give ["A7"] and "=Book1!A5+8" should give ["Book1!A5]
>
> > Ok, although "Book1" would be the default name of a workbook, with
> > default
> > worksheets labeled "Sheet1". "Sheet2", etc.
>
> > If I had a worksheet named "Sheety" that wanted to reference a cell on
> > "Sheetx"
> > OF THE SAME WORKBOOK, it would be =Sheet2!A7. If the reference was to
> > a completely
> > different workbook (say Book1 with worksheets labeled "Sheet1",
> > "Sheet2") then
> > the cell might have =[Book1]Sheet1!A7.
>
> > And don't forget the $'s! You may see =[Book1]Sheet1!$A$7.
>
> Yes, Mensanator, but... what re should I use? I'm looking for the re
> statement. No doubt you can help!
>
> Thank you.
Let me give you an example:
>>> import re
>>> re.split("([^0-9])", "123+456*/")
[’123’, ’+’, ’456’, ’*’, ’’, ’/’, ’’]
I find it excellent that one single statement is able to do a lexical
analysis of an expression!
If the expression contains variables, such as A12 or B9, I can try
another re expression. Which one should I use?
And if my expression contains parenthesis? And the sin() function?
Vicente Soler
--
http://mail.python.org/mailman/listinfo/python-list
Unable to install numpy
Hi all, I just download Numpy, and tried to install it using "numpy-1.4.0- win32-superpack-python2.6.exe" I get an error: "Python version 2.6 required, which was not found in the Registry" However, I am using Python 2.6 every day. I'm running Windows 7. What can I do? -- http://mail.python.org/mailman/listinfo/python-list
Listing variables
Say that a have: # file test.py a=7 At the prompt: import test dir() I would like to see the variables created in the test namespace. However, variable "a" does not appear in the list, only "test". Since I know that var "a" is reachable from the prompt by means of test.a, how can I list this sort of variables? Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Listing variables
On Oct 25, 12:01 pm, Tim Chase wrote:
> > Say that a have:
>
> > # file test.py
> > a=7
>
> > At the prompt:
> > import test
> > dir()
>
> > I would like to see the variables created in the test namespace.
> > However, variable "a" does not appear in the list, only "test". Since
> > I know that var "a" is reachable from the prompt by means of test.a,
> > how can I list this sort of variables?
>
> dir(test)
>
> works for any scope you want (except in some C modules...was
> peeved at mod_python for this reason when I was playing with it a
> while back). I use this for debugging all the time:
>
> dir(foo.bar.whatever)
>
> or if I want to remember some less-used method on a string/list/dict:
>
> dir("")
> dir([])
> dir({})
>
> -tkc
Tim,
If I just input dir(test) I don't get "a" in my list.
>>> import test
>>> dir(test)
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'__path__']
>>>
I am using python 2.6
Am I doing anything wrong?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Listing variables
On Oct 25, 1:32 pm, Tim Chase wrote: > > If I just input dir(test) I don't get "a" in my list. > > import test > dir(test) > > ['__builtins__', '__doc__', '__file__', '__name__', '__package__', > > '__path__'] > > > I am using python 2.6 > > > Am I doing anything wrong? > > Are you importing the module you think you are? > > t...@rubbish:~/tmp$ echo "a=42" > test.py > t...@rubbish:~/tmp$ python2.5 > >>> import test > >>> dir(test) > ['__builtins__', '__doc__', '__file__', '__name__', 'a'] > > Granted this is 2.5 (the most current I have on my Debian box, > but I also tested in 2.3 and 2.4 which are also installed) > instead of 2.6 but they should all behave the same. If I remove > test.py/test.pyc, I get the following: > > t...@rubbish:~/tmp$ rm test.py test.pyc > t...@rubbish:~/tmp$ python2.5 > >>> import test > >>> dir(test) > ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] > >>> test.__file__ > '/usr/lib/python2.5/test/__init__.pyc' > > because there's apparently a module named "test" in the standard > distribution that gets found instead. > > -tkc Tim, You were right. When I renamed my test.py file into test77.py it worked perfectly well. Thank you. Is there a way to know which test.py it was importing? -- http://mail.python.org/mailman/listinfo/python-list
Re: Listing variables
On Oct 25, 5:07 pm, Tim Chase wrote: > >> t...@rubbish:~/tmp$ rm test.py test.pyc > >> t...@rubbish:~/tmp$ python2.5 > >> >>> import test > >> >>> dir(test) > >> ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] > >> >>> test.__file__ > >> '/usr/lib/python2.5/test/__init__.pyc' > > >> because there's apparently a module named "test" in the standard > >> distribution that gets found instead. > > > You were right. When I renamed my test.py file into test77.py it > > worked perfectly well. Thank you. > > > Is there a way to know which test.py it was importing? > > well, as my simple code showed, you can check test.__file__ or > test.__path__ if you're curious. Python just searches through > your $PYTHONPATH which you can determine at runtime via sys.path > > -tkc Thank you Tim, everything is clear now. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
My own accounting python euler problem
In the accounting department I am working for we are from time to time confronted to the following problem: A customer sends us a check for a given amount, but without specifying what invoices it cancels. It is up to us to find out which ones the payment corresponds to. For example, say that the customer has the following outstanding invoices: $300, $200, $50; and say that the check is for $250. This time it is clear, the customer is paying bills $200 and $50. However, let's now say that the outstanding invoices are $300, $200, $100 and that the check is for $300. In this case there are already two possibilities. The customer is paying the $300 invoice or the $200 and $100. In other words, there is more than one solution to the problem. My first question is: 1. given a list of invoives I=[500, 400, 450, 200, 600, 700] and a check Ch=600 how can I print all the different combinations of invoices that the check is possibly cancelling 1.a. first approach using "brute force", that is, exploring all different combinations: every single invoice, all of 2-element tuples, 3-element tuples, etc... 1.b can all the solutions be found without exploring all possible combinations? some problems can be solved by discarding some invoices, for example those whose amounts are greater than the amount of the check. Any ideas? My second question is: 2. this time there are also credit notes outstanding, that is, invoices with negative amounts. For example, I=[500, 400, -100, 450, 200, 600, -200, 700] and a check Ch=600 2.a is the "brute force" method used in 1.a still applicable now that "I" contains negative values? 2.b same as 1.b. However, this time I can imagen that the number of invoices that can be discarded is a lot more reduced. I am a fan of Python, which I find very elegant, powerful and easy to develop with. I would like to find answers to the problems described above, partially because I am still learning python, and I would like to make use of it. Can anybody help? -- http://mail.python.org/mailman/listinfo/python-list
Re: My own accounting python euler problem
On Nov 8, 1:27 pm, Ozz wrote: > Robert P. J. Day schreef: > > > does your solution allow for the possibility of different invoices > > of equal amounts? i would be reluctant to use the word "subset" in a > > context where you can have more than one element with the same value. > > I think it handles different invoices of equal amounts correctly. > I agree with you though that the term subset may not be the best name in > this context because of those duplicates. > > cheers, > Ozz Ozz, Instead of subsets, do you mean permutations/combinations? Since 2 invoices can have the same amount perhaps the terms permutation is better. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Changing the current directory
Ever since I installed my Python 2.6 interpreter, I've been saving my *.py files in the C:\Program Files\Python26 directory, which is the default directory for such files in my system. However, I have realised that the above is not the best practice. Therefore I created the C:\Program Files\Python26\test directory and I want it to be my default directory for saving *.py files, importing modules, etc. I'd like to do something like the DOS equivalent of "CD test" but I do not know kow to do it. I am currently doing something really awful: I open a *.py file in the est subdirectory, I run it with the F5 key and it works! but I am doing really something stupid. I can see that it works because if I do -- http://mail.python.org/mailman/listinfo/python-list
Changing the current directory (full post)
Oops!!! something went wrong with my keyboard. Here you have my full post: Ever since I installed my Python 2.6 interpreter (I use IDLE), I've been saving my *.py files in the C:\Program Files\Python26 directory, which is the default directory for such files in my system. However, I have realised that the above is not the best practice. Therefore I created the C:\Program Files\Python26\test directory and I want it to be my default directory for saving *.py files, importing modules, etc. I'd like to do something like the DOS equivalent of "CD test" but I do not know kow to do it. I am currently doing something really awful: I open a *.py file in the test subdirectory, I run it with the F5 key and it works! but I am doing really something stupid. I can see that it works because if I do import sys sys.path ... the first directory in the list is the test one. How should I proceed, if I want to proceed properly? Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the current directory (full post)
On Nov 16, 2:35 am, "Gabriel Genellina" wrote: > En Sun, 15 Nov 2009 09:04:06 -0300, vsoler > escribió: > > > Ever since I installed my Python 2.6 interpreter (I use IDLE), I've > > been saving my > > *.py files in the C:\Program Files\Python26 directory, which is the > > default directory for such files in my system. > > > However, I have realised that the above is not the best practice. > > Therefore I created the C:\Program Files\Python26\test directory and I > > want it to be my default directory for saving *.py files, importing > > modules, etc. > > This is *not* a good place either. Non-privileged users should not have > write permission in the C:\Program Files directory. > > > I'd like to do something like the DOS equivalent of "CD test" but I > > do not know kow to do it. > > > I am currently doing something really awful: I open a *.py file in the > > test subdirectory, I run it with the F5 key and it works! but I am > > doing really something stupid. > > "it works!" What's the problem then? > > > How should I proceed, if I want to proceed properly? > > Sorry but I don't even see your problem. You can save your .py files > anywhere you like... > > -- > Gabriel Genellina Gabriel, When I enter IDLE, I'd like to say at the prompt: "my current directory is... ...test" and then be able to run a module in that directory. This is what my problem is!!! Thank you if you can help -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the current directory (full post)
On Nov 16, 8:45 pm, Chris Rebert wrote: > On Mon, Nov 16, 2009 at 11:36 AM, vsoler wrote: > > On Nov 16, 2:35 am, "Gabriel Genellina" > > wrote: > >> En Sun, 15 Nov 2009 09:04:06 -0300, vsoler > >> escribió: > > >> > Ever since I installed my Python 2.6 interpreter (I use IDLE), I've > >> > been saving my > >> > *.py files in the C:\Program Files\Python26 directory, which is the > >> > default directory for such files in my system. > > >> > However, I have realised that the above is not the best practice. > >> > Therefore I created the C:\Program Files\Python26\test directory and I > >> > want it to be my default directory for saving *.py files, importing > >> > modules, etc. > > >> This is *not* a good place either. Non-privileged users should not have > >> write permission in the C:\Program Files directory. > > >> > I'd like to do something like the DOS equivalent of "CD test" but I > >> > do not know kow to do it. > > >> > I am currently doing something really awful: I open a *.py file in the > >> > test subdirectory, I run it with the F5 key and it works! but I am > >> > doing really something stupid. > > >> "it works!" What's the problem then? > > >> > How should I proceed, if I want to proceed properly? > > >> Sorry but I don't even see your problem. You can save your .py files > >> anywhere you like... > > >> -- > >> Gabriel Genellina > > > Gabriel, > > > When I enter IDLE, I'd like to say at the prompt: "my current > > directory is... ...test" and then be able to run a module in that > > directory. This is what my problem is!!! > > 1. File -> Open > 2. Navigate to file and choose it > 3. Press F5 > > Cheers, > Chris > --http://blog.rebertia.com Say that you wanted to import a file in the test directory after just entering IDLE. How would you do it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Unable to install numpy
On Jan 18, 9:08 pm, Robert Kern wrote: > On 2010-01-18 14:02 PM, vsoler wrote: > > > Hi all, > > > I just download Numpy, and tried to install it using "numpy-1.4.0- > > win32-superpack-python2.6.exe" > > > I get an error: "Python version 2.6 required, which was not found in > > the Registry" > > > However, I am using Python 2.6 every day. I'm running Windows 7. > > > What can I do? > > Please ask numpy installation questions on the numpy mailing list. > > http://www.scipy.org/Mailing_Lists > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco Thank you Robert. I'm going to direct my questions towards scipy.org. However, since I do not find my questions already answered, could you tell me where to post it? I beg your pardon for still asking this question outside of scipy.org, but I've been unable to move on. Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Selecting a file in a directory
On Feb 14, 2:28 am, "Alf P. Steinbach" wrote: > * vsoler: > > > Hi, > > > My python script needs to work with a .txt file in a directory. I > > would like to give the user the possibility to choose the file he > > needs to work on in as much the same way as I open a .xls file in > > Excel, that is, I want to make appear the "Windows'" window and let > > the user choose. > > > I think this should be quite straightforward. > > > How should I proceed? > > At least in Windows one easy way is to delegate that responsibility to the > Windows shell. When a user drags a file onto your script, your script is run > with the path to that dragged file as argument. Or it can even be multiple > files. > > Otherwise, tkinter has, as I recall, a standard file chooser dialog. > > These "standard" dialogs are generally called "common dialogs". > > Just google for tkinter and suitable words. > > Cheers & hth., > > - Alf I'll try, thank you very much -- http://mail.python.org/mailman/listinfo/python-list
Re: Selecting a file in a directory
On Feb 14, 2:45 am, rantingrick wrote:
> On Feb 13, 7:28 pm, "Alf P. Steinbach" wrote:
>
>
>
> > * vsoler:
>
> > > Hi,
>
> > > My python script needs to work with a .txt file in a directory. I
> > > would like to give the user the possibility to choose the file he
> > > needs to work on in as much the same way as I open a .xls file in
> > > Excel, that is, I want to make appear the "Windows'" window and let
> > > the user choose.
>
> > > I think this should be quite straightforward.
>
> > > How should I proceed?
>
> > At least in Windows one easy way is to delegate that responsibility to the
> > Windows shell. When a user drags a file onto your script, your script is run
> > with the path to that dragged file as argument. Or it can even be multiple
> > files.
>
> > Otherwise, tkinter has, as I recall, a standard file chooser dialog.
>
> > These "standard" dialogs are generally called "common dialogs".
>
> specifically Alf was referring to tkFileDialog.askopenfilename().
> Heres an example...
>
> import Tkinter as tk
> from tkFileDialog import askopenfilename
>
> root = tk.Tk()
>
> def get_files():
> path = askopenfilename(filetypes=[('TXT', '.txt')])
> if path:
> print path
>
> tk.Button(root, text='1', font=('Wingdings', 12),
> command=get_files).pack(padx=5, pady=5)
>
> root.mainloop()
Excellent!!! Just what I needed!
--
http://mail.python.org/mailman/listinfo/python-list
Building a dict from a tuple of tuples
Hello everyone!
I have a tuple of tuples, coming from an Excel range, such as this:
((None, u'x', u'y'),
(u'a', 1.0, 7.0),
(u'b', None, 8.0))
I need to build a dictionary that has, as key, the row and column
header.
For example:
d={ (u'a',u'x'):1.0, (u'a',u'y'): 7.0, (u'b',u'y'):8.0 }
As you can see, if the value in the matrix is None, no key has to be
added to the dictionary.
Of course, my tuple of tuples is a lot bigger.
How can I possibly do this?
Thank you
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a dict from a tuple of tuples
On Feb 20, 7:00 pm, MRAB wrote:
> vsoler wrote:
> > Hello everyone!
>
> > I have a tuple of tuples, coming from an Excel range, such as this:
>
> > ((None, u'x', u'y'),
> > (u'a', 1.0, 7.0),
> > (u'b', None, 8.0))
>
> > I need to build a dictionary that has, as key, the row and column
> > header.
>
> > For example:
> > d={ (u'a',u'x'):1.0, (u'a',u'y'): 7.0, (u'b',u'y'):8.0 }
>
> > As you can see, if the value in the matrix is None, no key has to be
> > added to the dictionary.
>
> > Of course, my tuple of tuples is a lot bigger.
>
> > How can I possibly do this?
>
> > Thank you
>
> Does this help?
>
> matrix = ((None, u'x', u'y'),
> (u'a', 1.0, 7.0),
> (u'b', None, 8.0))
>
> for row in matrix[1 : ]:
> for col, val in zip(matrix[0][1 : ], row[1 : ]):
> print row[0], col, val
and the dictionary?
it is the ultimate goal of what I am intending...
Thank you
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building a dict from a tuple of tuples
On Feb 20, 8:54 pm, MRAB wrote:
> vsoler wrote:
> > On Feb 20, 7:00 pm, MRAB wrote:
> >> vsoler wrote:
> >>> Hello everyone!
> >>> I have a tuple of tuples, coming from an Excel range, such as this:
> >>> ((None, u'x', u'y'),
> >>> (u'a', 1.0, 7.0),
> >>> (u'b', None, 8.0))
> >>> I need to build a dictionary that has, as key, the row and column
> >>> header.
> >>> For example:
> >>> d={ (u'a',u'x'):1.0, (u'a',u'y'): 7.0, (u'b',u'y'):8.0 }
> >>> As you can see, if the value in the matrix is None, no key has to be
> >>> added to the dictionary.
> >>> Of course, my tuple of tuples is a lot bigger.
> >>> How can I possibly do this?
> >>> Thank you
> >> Does this help?
>
> >> matrix = ((None, u'x', u'y'),
> >> (u'a', 1.0, 7.0),
> >> (u'b', None, 8.0))
>
> >> for row in matrix[1 : ]:
> >> for col, val in zip(matrix[0][1 : ], row[1 : ]):
> >> print row[0], col, val
>
> > and the dictionary?
>
> > it is the ultimate goal of what I am intending...
>
> > Thank you
>
> The difficult bit is working out how to produce the keys and values for
> the dict from the tuple of tuples, and I've shown you that. The rest is
> straightforward.
I'll try. Thank you very much MRAB
--
http://mail.python.org/mailman/listinfo/python-list
Saving the Interactive Window with PythonWin
Hi everyone, When I run a python script, I know that I can print the results of my calculations on the Interactive Window. Once the scripts ends, I can copy/pate these results on an OpenOffice Writer document. However, I would like to know if I can somehow add some lines to my script, so that it saves the Interactive Window to a text file. How could it be done? And, is there a way to programatically clear out the Interactive Window so that it only shows the last run? Thank you for your help -- http://mail.python.org/mailman/listinfo/python-list
formatting a number as percentage
I'm trying to print .7 as 70%
I've tried:
print format(.7,'%%')
.7.format('%%')
but neither works. I don't know what the syntax is...
Can you help?
Thank you
--
http://mail.python.org/mailman/listinfo/python-list
Re: formatting a number as percentage
On Feb 21, 7:11 pm, TomF wrote:
> On 2010-02-21 09:53:45 -0800, vsoler said:
>
> > I'm trying to print .7 as 70%
> > I've tried:
>
> > print format(.7,'%%')
> > .7.format('%%')
>
> > but neither works. I don't know what the syntax is...
> >>> print "Grade is {0:%}".format(.87)
>
> Grade is 87.00%
>
> or if you want to suppress those trailing zeroes:
>
> >>> print "Grade is {0:.0%}".format(.87)
>
> Grade is 87%
Excellent, works perfect!!!
--
http://mail.python.org/mailman/listinfo/python-list
Re: formatting a number as percentage
On Feb 22, 8:32 pm, Hans Mulder wrote:
> Günther Dietrich wrote:
> > vsoler wrote:
>
> >> I'm trying to print .7 as 70%
> >> I've tried:
>
> >> print format(.7,'%%')
> >> .7.format('%%')
>
> >> but neither works. I don't know what the syntax is...
>
> > Did you try this:
>
> >>>> print('%d%%' % (0.7 * 100))
> > 70%
>
> That method will always round down; TomF's method will round to
> the nearest whole number:
>
> >>> print "%d%%" % (0.698 * 100)
> 69%
> >>> print "{0:.0%}".format(.698)
> 70%
>
> Only the OP knows which one is more appropriate for his use case.
>
> Hope this helps,
>
> -- HansM
Great!!!
Thank you
--
http://mail.python.org/mailman/listinfo/python-list
Creating variables from dicts
Hi,
I have two dicts
n={'a', 'm', 'p'}
v={1,3,7}
and I'd like to have
a=1
m=3
p=7
that is, creating some variables.
How can I do this?
--
http://mail.python.org/mailman/listinfo/python-list
Printing the arguments of an attribute in a class
I have a class that is a wrapper: class wrapper: def __init__(self, object): self.wrapped = object def __getattr__(self, attrname): print 'Trace: ', attrname #print arguments to attrname, how? return getattr(self.wrapped, attrname) I can run it this way: >>> x = wrapper([1,2,3]) >>> x.append(4) Trace: append >>> x.wrapped [1, 2, 3, 4] I am able to capture the attribute name to x (that is, append). However, I do not know how to capture and print all of its arguments (in this case number 4). How should I proceed? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing the arguments of an attribute in a class
On Feb 28, 4:00 pm, "Alf P. Steinbach" wrote: > * vsoler: > > > > > I have a class that is a wrapper: > > > class wrapper: > > def __init__(self, object): > > self.wrapped = object > > def __getattr__(self, attrname): > > print 'Trace: ', attrname > > #print arguments to attrname, how? > > return getattr(self.wrapped, attrname) > > > I can run it this way: > > >>>> x = wrapper([1,2,3]) > >>>> x.append(4) > > Trace: append > >>>> x.wrapped > > [1, 2, 3, 4] > > > I am able to capture the attribute name to x (that is, append). > > However, I do not know how to capture and print all of its arguments > > (in this case number 4). > > > How should I proceed? > > If your goal is just learning then in your __getattr__ you might return a > wrapper for the attribute instead of the attribute itself. Equip the wrapper > with a __call__ method if it is a method. And equip it with other special > methods as appropriate. > > I can imagine that that approach will lead to some practical problems, but it > may be great for learning. > > If your goal is tracing, then I suggest looking at the "trace" module. > > If your goal is something else purely practical, like intercepting method > calls > to do arbitrary things (logging, marshaling, whatever) then I suspect that it > might getspretty complicated, hairy. For specific method calls you might just > use subclassing, but for doing this in general, parameterized, you'd need to > about the same kinds of things as the trace module does. So I guess then one > idea might be to look at the source code of that module. > > But if that's what you intend to do, then best check first if there is an > existing solution. ParcPlace did this thing for a number of languages and > introduced a special term for it, I can't recall but something like > "cross-whatever mumbo jumbo concerns" plus one single catchy name. There might > be an existing Python implementation. > > Cheers & hth., > > - Alf Alf, My goal is just learning. In the code provided in the post I just can't think of a method to "see", "capture" or "use" the parameters. I am going to study the __call__ method and see if I can figure out how I can capture the parameters. Thank you Alf -- http://mail.python.org/mailman/listinfo/python-list
a simple def how-to
Hello,
My script starts like this:
book=readFromExcelRange('book')
house=readFromExcelRange('house')
table=readFromExcelRange('table')
read=readFromExcelRange('read')
...
But I would like to have something equivalent, like...
ranges=['book','house','table','read']
for i in ranges:
var[i]=readFromExcelRange(i)
which does not work. I assume I should be using globals() instead of
var, but I do not know how to write my script.
Can anybody help?
--
http://mail.python.org/mailman/listinfo/python-list
Re: a simple def how-to
On 7 mar, 16:23, Andreas Waldenburger wrote:
> On Sun, 7 Mar 2010 07:05:26 -0800 (PST) vsoler
>
>
>
> wrote:
> > Hello,
>
> > My script starts like this:
>
> > book=readFromExcelRange('book')
> > house=readFromExcelRange('house')
> > table=readFromExcelRange('table')
> > read=readFromExcelRange('read')
> > ...
>
> > But I would like to have something equivalent, like...
>
> > ranges=['book','house','table','read']
> > for i in ranges:
> > var[i]=readFromExcelRange(i)
>
> > which does not work. I assume I should be using globals() instead of
> > var, but I do not know how to write my script.
>
> > Can anybody help?
>
> One additional line, and it works (all the following code is untested,
> I might have goofed it up somewhere, but you get the idea):
>
> ranges=['book','house','table','read']
> var = {}
> for i in ranges:
> var[i]=readFromExcelRange(i)
>
> Or, more succinctly:
>
> var = dict((i, readFromExcelRange(i)) for i in ranges)
>
> although that looks a bit crowded. Perhaps
>
> rd = readFromExcelRange
> var = dict((i, rd(i)) for i in ranges)
>
> looks better, but not by much, IMO.
>
> In Python 3 you can also just say
>
> var = {i:readFromExcelRange(i) for i in ranges}
>
> (I think. I don't have Python 3.) This looks comparatively neat,
> because there are no nesting parens.
>
> And just in case you think it's a good idea to meddle with globals and
> create actual "variables": it's not. You absolutely want dictionaries
> here. It's basically a bad idea to create names *implicitly* that
> you're going to use *explicitly*. (That is, it is in Python anyway,
> because it does not provide a clean and clear way of doing this. Other
> languages might provide that sort of thing, and it might be awesome,
> but in Python, no sir.)
>
> /W
>
> --
> INVALID? DE!
Thank you Andreas.
Your comprehensive answer makes a lot of sense to me.
--
http://mail.python.org/mailman/listinfo/python-list
Re: a simple def how-to
On 7 mar, 16:23, John Posner wrote:
> On 3/7/2010 10:05 AM, vsoler wrote:
>
>
>
> > Hello,
>
> > My script starts like this:
>
> > book=readFromExcelRange('book')
> > house=readFromExcelRange('house')
> > table=readFromExcelRange('table')
> > read=readFromExcelRange('read')
> > ...
>
> > But I would like to have something equivalent, like...
>
> > ranges=['book','house','table','read']
> > for i in ranges:
> > var[i]=readFromExcelRange(i)
>
> > which does not work. I assume I should be using globals() instead of
> > var, but I do not know how to write my script.
>
> > Can anybody help?
>
> var = [] # create empty list
> for i in ranges:
> var.append(readFromExcelRange(i))
>
> -or-
>
> var = [ readFromExcelRange(i) for i in ranges ]
>
> -or-
>
> var = map(readFromExcelRange, ranges)
>
> -John
John,
Thank you for your help. Perhaps the solution you are suggesting is
not exactly what I was looking for, but helped anyway.
--
http://mail.python.org/mailman/listinfo/python-list
Duplicate keys in dict?
Hello,
My code snippet reads data from excel ranges. First row and first
column are column headers and row headers respectively. After reding
the range I build a dict.
'A'..'B'
'ab'35
'cd'72
'cd'91
'ac'72
d={('ab','A'): 3, ('ab','B'): 5, ('cd','A'): 7, ...
However, as you can see there are two rows that start with 'cd', and
dicts, AFAIK do not accept duplicates.
What is the best workaround for this? Should I discard dicts? Should I
somehow have under 'cd'... a list of values?
One of the difficulties I find here is that I want to be able to
easily sum all the values for each row key: 'ab', 'cd' and 'ac'.
However, using lists inside dicts makes it a difficult issue for me.
What is the best approach for this problem? Can anybody help?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Duplicate keys in dict?
On 7 mar, 17:53, Steven D'Aprano wrote:
> On Sun, 07 Mar 2010 08:23:13 -0800, vsoler wrote:
> > Hello,
>
> > My code snippet reads data from excel ranges. First row and first column
> > are column headers and row headers respectively. After reding the range
> > I build a dict.
>
> > 'A'..'B'
> > 'ab'35
> > 'cd'72
> > 'cd'91
> > 'ac'72
>
> > d={('ab','A'): 3, ('ab','B'): 5, ('cd','A'): 7, ...
>
> > However, as you can see there are two rows that start with 'cd', and
> > dicts, AFAIK do not accept duplicates.
> > One of the difficulties I find here is that I want to be able to easily
> > sum all the values for each row key: 'ab', 'cd' and 'ac'. However,
> > using lists inside dicts makes it a difficult issue for me.
>
> Given the sample above, what answer do you expect for summing the 'cd'
> row? There are four reasonable answers:
>
> 7 + 2 = 9
> 9 + 1 = 10
> 7 + 2 + 9 + 1 = 19
> Error
>
> You need to decide what you want to do before asking how to do it.
>
> --
> Steven
Steven,
What I need is that sum(('cd','A')) gives me 16, sum(('cd','B')) gives
me 3.
I apologize for not having made it clear.
--
http://mail.python.org/mailman/listinfo/python-list
print formatting
Hello, My script contains a print statement: print '%40s %15d' % (k, m) However, 1- the string is right adjusted, and I would like it left adjusted 2- the number is a decimal number, and I would like it with the thousands separator and 2 decimals If possible, the thousands separator and the decimal separator should use my local settings. Is there any way to achieve this? -- http://mail.python.org/mailman/listinfo/python-list
building a dict
Say that "m" is a tuple of 2-tuples
m=(('as',3), ('ab',5), (None, 1), ('as',None), ('as',6))
and I need to build a "d" dict where each key has an associated list
whose first element is the count, and the second is the sum. If a 2-
tuple contains a None value, it should be discarded.
The expected result is:
d={'as':[2, 9], 'ab': [1,5]}
How should I proceed? So far I have been unsuccessful. I have tried
with a "for" loop.
Thank you for your help
--
http://mail.python.org/mailman/listinfo/python-list
Re: building a dict
On 13 mar, 18:16, [email protected] wrote: > On Mar 13, 9:26 am, [email protected] wrote:> That should be: > > d = {} > > for item in m: > > key = item[0]; value = item[1] > > > if key is None or value is None: continue > > if key not in dict: > > d[key] = [1, value] > > else: > > d[key][0] += 1 > > d[key][1] += value > > That's it. Any other mistakes, you find 'em. Thank you all. Your answers are more than valuable to me. I'll study them carefully, but no doubt, my post has been answered. By the way, I suppose I am the OP. Since I am not an native English speaking person, I do not know what it stands for. Perhaps you can tell me. >From what I see from your posts, you would have preferred that I included in my original post my "for loop", so that the post is not so abstract. I have taken note and I'll make it better next time. Thank you for your help. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
"Breaking" the __main__ script
Hello, I am still learning python, thus developnig small scripts. Some of them consist only of the main module. While testing them (debugging) I sometimes want to stop the script at a certain point, with something likestop, break, end or something similar. What statement can I use? Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
iterator/generator
I am working on a script that reads data from an excel workbook. The
data is located in a named range whose first row contains the headers.
It works!!! I find it superb that python is able to do such things!!!
Now my questions.
a. My ranges can in practice be quite big, and although I am happy
with the speed I get, because I am learning python, I think I could do
it still a bit better. I think that the line for i in matriz[1:]:
could be improved with an iterator/generator, but I am not quite
certain how I should proceed.
b. the following lines could be improved by means of a defaultdict,
that I know because of a previous post. However you may come up with
some other ideas (this b. question is not my main concern, you may
discard it if you find the post too long)
if i[a] and not(i[a] in g) and i[b]:
g[i[a]] = i[b]
elif i[a] and (i[a] in g) and i[b]:
g[i[a]] += i[b]
Can anybody provide some hints? Thank you for your cooperation.
+++
+
import win32com.client as win32
def agrupar(matriz, c1, c2):
a, b = matriz[0].index(c1), matriz[0].index(c2)
g = {}
for i in matriz[1:]:
if i[a] and not(i[a] in g) and i[b]:
g[i[a]] = i[b]
elif i[a] and (i[a] in g) and i[b]:
g[i[a]] += i[b]
for k in g:
print '%-50s %15d' % (k, g[k])
# Abrir fichero excel
xl = win32.gencache.EnsureDispatch('Excel.Application')
##xl.Visible = True
wb=xl.Workbooks.Open(r'C:\Users\Vicente\Documents\VS\Python
\Presupuesto fijos 10YP 2011-2020 V0.xls')
# Obtención de datos
datos=wb.Names('Datos').RefersToRange()
print
agrupar(datos, u'NomCC', u'BGT-09')
# Cerrar libro de trabajo
wb.Close()
print
--
http://mail.python.org/mailman/listinfo/python-list
Clearing memory (namespace) before running code
Hi, Is there a way to erase/delete/clear memory before a piece of code is run? Otherwise, the objects of the previous run are re-usable, and may bring confusion to the tester. Thank you -- http://mail.python.org/mailman/listinfo/python-list
function decorator-like function
Hi, Still learning Python, now decorators. Before diving deeply into decorators, I'd like to apply a function to another function. My "extremely simple function" should print number 3, then the sum of its 2 arguments. Say that I call f(5,7) I'd like to get, somehow, 3 then 12. I've tried the following: def d(f): print 3 return f def f(a, b): print a+b f=d(f) However, it does not work. Calling f(5,7) only returns 12, (3 is missing) How should I proceed? -- http://mail.python.org/mailman/listinfo/python-list
Re: function decorator-like function
On 27 mar, 17:06, Patrick Maupin wrote: > On Mar 27, 10:24 am, vsoler wrote: > > > > > Hi, > > > Still learning Python, now decorators. > > > Before diving deeply into decorators, I'd like to apply a function to > > another function. > > > My "extremely simple function" should print number 3, then the sum of > > its 2 arguments. > > > Say that I call f(5,7) > > I'd like to get, somehow, 3 then 12. > > > I've tried the following: > > > def d(f): > > print 3 > > return f > > > def f(a, b): > > print a+b > > > f=d(f) > > > However, it does not work. Calling f(5,7) only returns 12, (3 is > > missing) > > How should I proceed? > >>> def d(f): > > ... def wrapper(*args): > ... print 3 > ... return f(*args) > ... return wrapper > ...>>> def f(a, b): > > ... print a + b > ...>>> f = d(f) > >>> f(5, 7) > > 3 > 12 > > HTH, > Pat Pat, I think some lines are missing. I don't see "d" function defined. Any lines above def wrapper? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: function decorator-like function
On 27 mar, 17:21, vsoler wrote: > On 27 mar, 17:06, Patrick Maupin wrote: > > > > > On Mar 27, 10:24 am, vsoler wrote: > > > > Hi, > > > > Still learning Python, now decorators. > > > > Before diving deeply into decorators, I'd like to apply a function to > > > another function. > > > > My "extremely simple function" should print number 3, then the sum of > > > its 2 arguments. > > > > Say that I call f(5,7) > > > I'd like to get, somehow, 3 then 12. > > > > I've tried the following: > > > > def d(f): > > > print 3 > > > return f > > > > def f(a, b): > > > print a+b > > > > f=d(f) > > > > However, it does not work. Calling f(5,7) only returns 12, (3 is > > > missing) > > > How should I proceed? > > >>> def d(f): > > > ... def wrapper(*args): > > ... print 3 > > ... return f(*args) > > ... return wrapper > > ...>>> def f(a, b): > > > ... print a + b > > ...>>> f = d(f) > > >>> f(5, 7) > > > 3 > > 12 > > > HTH, > > Pat > > Pat, > > I think some lines are missing. I don't see "d" function defined. Any > lines above def wrapper? > > Thank you Patrick, I see what happened. The first line was somehow hidden. Thank you very much. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
On Class namespaces, calling methods
Still learning python, especially OOP. While testing classes, I sometimes think of them as "ordinary containers" of values and functions (methods). That is, values and functions can be grouped together inside "namespaces" calles classes. class Uno: a=1 def m(): print "mouse" Say that I have this "silly" class. While I can then write print Uno.a I cannot write Uno.m() I get the following error message: TypeError: m() takes no arguments (1 given) Since I have not created any instances of Uno, there is no self object, and I do not understand what object is supplied to the function call. Could anybody explain what argument is being supplied to the method? Is ther any workaround to call the m function? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Clearing memory (namespace) before running code
On Mar 21, 5:18 pm, Jon Clements wrote: > On 21 Mar, 15:02, vsoler wrote: > > > Hi, > > > Is there a way to erase/delete/clear memory before a piece of code is > > run? > > > Otherwise, the objects of the previous run are re-usable, and may > > bring confusion to the tester. > > > Thank you > > I'm guessing you're using some sort of IDE? > > For instance, in IDLE if the [Python Shell] window is not closed, the > session is kept. However, there is a menu option 'Shell' which has > 'Restart Shell'. If you don't see a 'Shell' menu option, then make > sure IDLE isn't being started with the -n option. > > However I would have thought the 'tester' would be running from a > terminal/command line/double click jobby, so that a single Python > session is executed and just runs -- rather than want to use it > interactively afterwards. > > hth > > Jon. Hello Jon, I'm using PythonWin and there is no Shell menu option. And yes, I am using python interactively. Perhaps it is simply impossible to delete all the attributes of a namespace in a single shot? -- http://mail.python.org/mailman/listinfo/python-list
Re: On Class namespaces, calling methods
On Apr 10, 4:46 pm, Duncan Booth wrote: > vsoler wrote: > > I get the following error message: > > > TypeError: m() takes no arguments (1 given) > > > Since I have not created any instances of Uno, there is no self > > object, and I do not understand what object is supplied to the > > function call. > > > Could anybody explain what argument is being supplied to the method? > > Is ther any workaround to call the m function? > > Which version of Python are you using? Python 2.6 gives: > > TypeError: unbound method m() must be called with Uno instance as first > argument (got nothing instead) > > whereas Python 3.1 gives: > > >>> Uno.m() > > mouse > > (assuming you change the print statement to work on Python 3.x) Hello Duncan, I am using ver 2.6, under PythonWin The feedback that I get from python is exactly this one: >>> print Uno.a 1 >>> Uno.m() Traceback (most recent call last): File "", line 1, in TypeError: m() takes no arguments (1 given) >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: On Class namespaces, calling methods
On Apr 10, 4:46 pm, Duncan Booth wrote: > vsoler wrote: > > I get the following error message: > > > TypeError: m() takes no arguments (1 given) > > > Since I have not created any instances of Uno, there is no self > > object, and I do not understand what object is supplied to the > > function call. > > > Could anybody explain what argument is being supplied to the method? > > Is ther any workaround to call the m function? > > Which version of Python are you using? Python 2.6 gives: > > TypeError: unbound method m() must be called with Uno instance as first > argument (got nothing instead) > > whereas Python 3.1 gives: > > >>> Uno.m() > > mouse > > (assuming you change the print statement to work on Python 3.x) Hello Duncan, Your error message is correct if you use class Uno(object): However, the error message is different underclass Uno: Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: On Class namespaces, calling methods
On Apr 10, 5:28 pm, Laszlo Nagy wrote: > > class Uno: > > a=1 > > def m(): > > print "mouse" > > > Say that I have this "silly" class. > > > While I can then write > > > print Uno.a > > > I cannot write > > Uno.m() > > > I get the following error message: > > > TypeError: m() takes no arguments (1 given) > > As a workaround, use this pattern: > > >>> class Uno(object): > ... @classmethod > ... def m(cls): > ... print "mouse" > ... > >>> Uno.m() > mouse > > > Since I have not created any instances of Uno, there is no self > > object, and I do not understand what object is supplied to the > > function call. > > The method is not actually called, so nothing is supplied. The error is > raised when it turns out that the number of actual parameters and the > number of formal parameters are different. > > This is how you call a method: > > #1. you try to call Uno.m() - the 'm' method object is found and taken > #2. argument values are evaluated and taken (in your example, there are > no arguments) > #3. an extra argument is inserted in front of the argument list. This > parameter is the object you where calling the method on. In this case, > it is the 'Uno' class. > #4. actual arguments are assigned to formal parameters. If this fails > for some reason, an exception is raised. In your case - the number of > actual parameters is one, the number of formal parameters is zero. This > is why you get an exception. > #5. If actual and formal parameters are matched, then the implicit self > parameter is checked. If you call a method, then it must be an instance > of the class being called (or an instanc of its subclass). For > classmethods, it must be the same class (or a subclass of it). > #6. Function body executed, value returned > > The implicit parameter (the instance, or for classmethods, the class) is > ALWAYS added. So if you change your code: > > class Uno: > def m(self): > pass > > Then you won't get an exception in #4. But you will in #5, because > instance methods must be called on an instance, not on a class. You can > create a classmethod (e.g. with the @classmethod decorator) as shown > above, and it will work. > > > Could anybody explain what argument is being supplied to the method? > > Is ther any workaround to call the m function? > > > Thank you > > Hi Laszlo, It's perfectly clear. Thank you very much -- http://mail.python.org/mailman/listinfo/python-list
Extracting an undefined number of items from a list
Hi everyone, say that 'db' is a list of values say 'i' is a list of indexes I'd like to get a list where each item is i-th element of db. For example: db=[10,20,30,40,50,60,70,80,90] #undefined length i=[3,5,7] #undefined length then result=[30,50,70] # resulting list how can I do this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting an undefined number of items from a list
On 12 abr, 22:11, Patrick Maupin wrote: > On Apr 12, 3:05 pm, vsoler wrote: > > > Hi everyone, > > > say that 'db' is a list of values > > say 'i' is a list of indexes > > I'd like to get a list where each item is i-th element of db. > > > For example: > > > db=[10,20,30,40,50,60,70,80,90] #undefined length > > i=[3,5,7] #undefined length > > then result=[30,50,70] # resulting list > > > how can I do this? > > With a list comprehension: > > >>> db=[10,20,30,40,50,60,70,80,90] > >>> i=[3,5,7] > >>> [db[x-1] for x in i] > > [30, 50, 70] > > Regards, > Pat Thank you Patrick, Your quick answer only tells me how much I still have to learn. -- http://mail.python.org/mailman/listinfo/python-list
Calling a class method
I have the following script: class TTT(object): def duplica(self): self.data *= 2 def __init__(self, data): self.data = data TTT.duplica(self.data) def __str__(self): return str(self.data) print obj=TTT(7) print obj And I want 14 printed (twice 7) I got the following error: TypeError: unbound method duplica() must be called with TTT instance as first argument (got int instance instead) What am I doing wrong? -- http://mail.python.org/mailman/listinfo/python-list
global variables in imported modules
Taken from www.python.org, FAQ 2.3 How do I share global variables across modules? config.py: x = 0 # Default value of the 'x' configuration setting mod.py: import config config.x = 1 main.py: import config # try removing it import mod print config.x The example, such as shown in the website, works perfectly well. However, I don't fully understand why I have to import config in main.py, since it has already been imported by mod.py. As the website explains, there is only one module namespace for each module, and mod.py has aleady created the config namespace by importing it. Why should I import it again in main.py if that namespace already exists? If I remove -> import config # try removing it in main.py, the application does not run What am I missing? -- http://mail.python.org/mailman/listinfo/python-list
Re: global variables in imported modules
On 17 mayo, 00:05, Patrick Maupin wrote: > On May 16, 4:42 pm, vsoler wrote: > > > > > Taken fromwww.python.org, FAQ 2.3 How do I share global variables > > across modules? > > > config.py: > > > x = 0 # Default value of the 'x' configuration setting > > > mod.py: > > > import config > > config.x = 1 > > > main.py: > > > import config # try removing it > > import mod > > print config.x > > > The example, such as shown in the website, works perfectly well. > > However, I don't fully understand why I have to import config in > > main.py, since it has already been imported by mod.py. > > > As the website explains, there is only one module namespace for each > > module, and mod.py has aleady created the config namespace by > > importing it. Why should I import it again in main.py if that > > namespace already exists? > > > If I remove -> import config # try removing it in main.py, > > the application does not run > > > What am I missing? > > What you are missing is that the interpreter has to look *inside* a > namespace in order to actually find the object associated with a > name. As you found out, there is a namespace per module. So > main.py's namespace is where the code in main.py will search for > variables. If 'mod' imports config, then the 'mod' module's namespace > is updated with 'config' -> the config module. But the act of 'mod' > importing 'config' will not alter the namespace of 'main' at all. So > if you want to access variable 'x' inside 'config' from main you can > either import config directly into main and access it as config.x, or > you can import config into mod and import mod into main and access it > as mod.config.x. > > Regards, > Pat Thank you Pat, it's very clear. However, can I be 100% sure that,no matter how I access variable 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean that either reference of 'x' points to the same id(memory position)? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: global variables in imported modules
On 17 mayo, 00:38, James Mills wrote: > On Mon, May 17, 2010 at 8:26 AM, vsoler wrote: > > However, can I be 100% sure that,no matter how I access variable > > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean > > that either reference of 'x' points to the same id(memory position)? > > Yes it does unless you re-assign it. > > --James Understood, thank you very much Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: global variables in imported modules
On 17 mayo, 00:52, Patrick Maupin wrote: > On May 16, 5:38 pm, James Mills wrote: > > > On Mon, May 17, 2010 at 8:26 AM, vsoler wrote: > > > However, can I be 100% sure that,no matter how I access variable > > > 'x' (with config.x or mod.config.x) it is always the same 'x'. I mean > > > that either reference of 'x' points to the same id(memory position)? > > > Yes it does unless you re-assign it. > > > --James > > To expand a bit on what James is saying: > > If, for example, inside your main module, you got tired of typing > "mod.config.x" everywhere you were using it, and decided that you > could make a local reference to the same variable: > > x = mod.config.x > > Now, whenever you use just plain x inside the main module, you are > also referencing the exact same object, *until* some other function > decides to do: > > mod.config.x = y > > At this point in time, the 'x' inside main references the object that > mod.config.x originally referenced, but mod.config.x now references a > different object. > > Unlike C, for example, where the assignment operator physically places > an item into a specific memory location (either fixed globally or > within a stack frame), the assignment operator in python simply stores > a key/value pair into a namespace dictionary. So whenever you > retrieve a value from the dictionary using that key, you will get the > value that was last associated with that key. > > So, 'mod.config.x' will first retrieve the object associated with the > key 'mod' from the main module's namespace dictionary, then will > retrieve the object associated with the key 'config' from that > module's namespace dictionary, then will retrieve the object > associated with the key 'x' from that module's namespace dictionary. > Unless you later modify any of those key/value pairs, subsequent > retrieval will always result in the same final value. > > Regards, > Pat Really interesting, it helps a lot. Thank you -- http://mail.python.org/mailman/listinfo/python-list
The Application cannot locate win32ui.pyd (or Python) (126)
Hi all, I just installed python 3.1.2 where I used to have python 2.6.4. I'm working on Win7. The IDLE GUI works, but I get the following message when trying to open *.py files written for py 2.6 The Application cannot locate win32ui.pyd (or Python) (126) Should I change the PATH in Windows? Should I change the PYTHONPATH? I am a bit lost. Everything worked fine with 2.6. Moreover, when I try to open an old *.py file, I sometimes get a message saying that the file should be converted to UTF-8. What does this mean? I'm also trying to use the 2to3 converter, but I cannot see where the converted files are written to! Any help is highly appreciated. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: The Application cannot locate win32ui.pyd (or Python) (126)
On Aug 4, 5:41 pm, Alex Willmer wrote: > On Aug 4, 2:35 pm, vsoler wrote: > > > Hi all, > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > working on Win7. > > > The IDLE GUI works, but I get the following message when trying to > > open *.py files written for py 2.6 > > > The Application cannot locate win32ui.pyd (or Python) (126) > > win32ui is part of the PyWin32 package. Most likely you have a version > of PyWin32 for Python 2.6 installed, you should uninstall that and > install PyWin32 for Python 3.1. Downloads are > athttp://sourceforge.net/projects/pywin32/files/ > > You should do the same for any other third party packages that are > installed. > > > Moreover, when I try to open an old *.py file, I sometimes get a > > message saying that the file should be converted to UTF-8. What does > > this mean? > > Those files contain non-ascii characters (e.g. £, €, æ). Non-ascii > characters must be encoded when saved using and encoding. UTF-8 is one > such encoding, and it was chosen as the default .py encoding for > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > text editor, or declare the encoding so Python 3 knows it. More info: > > http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python.org/howto/unicode > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > converted files are written to! > > I think 2to3 prints a diff of the file changes to the console. The -w > command line option should modify files in place. Thank you Alex for your detailes reply. Before switching to Python 3.1.2 I removed all my Python 2.6 packages (python, pywin32, numpy, wxpython). However, the removal was not complete since some files could not be removed. Additionally, I still see my C:\python26 directory which is suposed not to exist any longer. If I go to the Control Panel, I cannot see any of the above suposedly removed programs as pending of removal, so I really do not know what more to do. I was even thinking of removing the C:\python26 directory with the Supr key, but I always heard that it is not a good idea, the Registry could become inconsistent. Additionally, I have not found in my Win7 system nay utility for fixing it, should it become corrupt. Perhaps my questions concern a bit more the Operating system (windows) than they do python, but since I am fond of python and I definitely would like to become somehow proficient at it, I would like to solve the problem that I have. I would not like to take a lot of your time, but, do you have any hints as to what I should do to 'tune' my PC? Thank you very much for your help. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: The Application cannot locate win32ui.pyd (or Python) (126)
On Aug 4, 7:52 pm, Alex Willmer wrote: > On Aug 4, 5:19 pm, vsoler wrote: > > > > > On Aug 4, 5:41 pm, Alex Willmer wrote: > > > > On Aug 4, 2:35 pm, vsoler wrote: > > > > > Hi all, > > > > > I just installed python 3.1.2 where I used to have python 2.6.4. I'm > > > > working on Win7. > > > > > The IDLE GUI works, but I get the following message when trying to > > > > open *.py files written for py 2.6 > > > > > The Application cannot locate win32ui.pyd (or Python) (126) > > > > win32ui is part of the PyWin32 package. Most likely you have a version > > > of PyWin32 for Python 2.6 installed, you should uninstall that and > > > install PyWin32 for Python 3.1. Downloads are > > > athttp://sourceforge.net/projects/pywin32/files/ > > > > You should do the same for any other third party packages that are > > > installed. > > > > > Moreover, when I try to open an old *.py file, I sometimes get a > > > > message saying that the file should be converted to UTF-8. What does > > > > this mean? > > > > Those files contain non-ascii characters (e.g. £, €, æ). Non-ascii > > > characters must be encoded when saved using and encoding. UTF-8 is one > > > such encoding, and it was chosen as the default .py encoding for > > > Python 3.x. Those files are probably in iso8859, cp432, or perhaps > > > UTF-16 (aka UCS-2). You can save them in UTF-8 using your favourite > > > text editor, or declare the encoding so Python 3 knows it. More info: > > > >http://www.joelonsoftware.com/articles/Unicode.htmlhttp://docs.python... > > > > > I'm also trying to use the 2to3 converter, but I cannot see where the > > > > converted files are written to! > > > > I think 2to3 prints a diff of the file changes to the console. The -w > > > command line option should modify files in place. > > > Thank you Alex for your detailes reply. > > > Before switching to Python 3.1.2 I removed all my Python 2.6 packages > > (python, pywin32, numpy, wxpython). However, the removal was not > > complete since some files could not be removed. Additionally, I still > > see my C:\python26 directory which is suposed not to exist any longer. > > It probably contains one or two files the installers weren't aware of. > E.g. a module you added manually, a log, a .pyc > > > I would not like to take a lot of your time, but, do you have any > > hints as to what I should do to 'tune' my PC? > > Take a backup then either delete the Python26 directory, or rename it. > Any problems, reverse the process. Thank you very much Alex -- http://mail.python.org/mailman/listinfo/python-list
Reading the access attributes of directories in Windows
Hello everyone! I need to read, for each of the directories in a shared file server unit, who has access to the directories and what type of access privileges. This is something that I can easily do interactively in my Windows Document Explorer by right clicking a single directory, clicking on Properties, then on Security. There I can see the Users and Group of Users that have access to the selected directory, as well as the type of access to that directory (Read/Write/eXecute etc.) Since I have to prepare a new access scheme, I first need to read what the current situation is. I've been looking in the "os" library, and found the "os.chmod" method but I am not sure that it is going to give me what I need. Should I also used library "stat"? So far I have not been able to find my way to the solution of this problem. Googling the web, I have seen that some examples provive some kind of information but using codes (755 or 0577) that I shoud translate to some form of understandable text messages. I think that my problem consists of finding the correct library/method to get the solution. Can anybody help? Thank you Using Python 3.1 on Windows Vista -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 19, 8:55 pm, Tim Golden wrote: > On 19/08/2010 4:55 PM, vsoler wrote: > > > I need to read, for each of the directories in a shared file server > > unit, who has access to the directories and what type of access > > privileges. > > > This is something that I can easily do interactively in my Windows > > Document Explorer by right clicking a single directory, clicking on > > Properties, then on Security. > > > There I can see the Users and Group of Users that have access to the > > selected directory, as well as the type of access to that directory > > (Read/Write/eXecute etc.) > > Here you have one of those occasions when the Windows GUI does > a very good job of presenting a simplified but perfectly usable > interface layer on top of a moderately complex security scheme. > > It's not as easy as you think. > > > I've been looking in the "os" library, and found the "os.chmod" method > > but I am not sure that it is going to give me what I need. Should I > > also used library "stat"? > > No. Both of these are basically doing a best-endeavours job of mapping > certain Windows attributes to some Posix equivalent. They're essentially > useless for anything beyond the most trivial tasks. > > Have a read here which will at least put you on the path of knowing > what terminology you need to search for: > > http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html > http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file > > and if you're interested, this is the kind of thing my winsys > package is reasonably good at: > > http://timgolden.me.uk/python/winsys/security.html#module-security > > TJG Thank you very much, Tim, for your answer. It looks as though it is going to suit my needs. Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and 2.6. File WinSys-0.4.zip should be for the same versions of Python, probably. What about your WinSys-0.5beta.win32.exe file? is it for python 3? I currently have python 3 in my pc. Do I need to install a previous version of python? Thank you for your help Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 19, 10:59 pm, Tim Golden wrote: > On 19/08/2010 9:17 PM, vsoler wrote: > > > > > On Aug 19, 8:55 pm, Tim Golden wrote: > >> On 19/08/2010 4:55 PM, vsoler wrote: > > >>> I need to read, for each of the directories in a shared file server > >>> unit, who has access to the directories and what type of access > >>> privileges. > > >>> This is something that I can easily do interactively in my Windows > >>> Document Explorer by right clicking a single directory, clicking on > >>> Properties, then on Security. > > >>> There I can see the Users and Group of Users that have access to the > >>> selected directory, as well as the type of access to that directory > >>> (Read/Write/eXecute etc.) > > >> Here you have one of those occasions when the Windows GUI does > >> a very good job of presenting a simplified but perfectly usable > >> interface layer on top of a moderately complex security scheme. > > >> It's not as easy as you think. > > >>> I've been looking in the "os" library, and found the "os.chmod" method > >>> but I am not sure that it is going to give me what I need. Should I > >>> also used library "stat"? > > >> No. Both of these are basically doing a best-endeavours job of mapping > >> certain Windows attributes to some Posix equivalent. They're essentially > >> useless for anything beyond the most trivial tasks. > > >> Have a read here which will at least put you on the path of knowing > >> what terminology you need to search for: > > >> http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html > >> http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file > > >> and if you're interested, this is the kind of thing my winsys > >> package is reasonably good at: > > >> http://timgolden.me.uk/python/winsys/security.html#module-security > > >> TJG > > > Thank you very much, Tim, for your answer. > > > It looks as though it is going to suit my needs. > > > Your file WinSys-0.4.win32-py2.5.msi is obviously for python 2.5 and > > 2.6. > > File WinSys-0.4.zip should be for the same versions of Python, > > probably. > > What about your WinSys-0.5beta.win32.exe file? is it for python 3? > > > I currently have python 3 in my pc. Do I need to install a previous > > version of python? > > > Thank you for your help > > > Vicente Soler > > I have a subversion branch for Python 3. If you have subversion > access, try: > > http://winsys.googlecode.com/svn/branches/py3k > > and do the python setup.py install dance. > > If you can't get that working, let me know and I'll publish > an installer somewhere. > > TJG I currently do not have subversion access in my PC. I could try to install a free copy of it. But it you could ptovide an installer, it certainly would do things easier. Please let me know if it is possible. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 20, 9:36 am, Tim Golden wrote: > > I currently do not have subversion access in my PC. I could try to > > install a free copy of it. But it you could ptovide an installer, it > > certainly would do things easier. Please let me know if it is > > possible. > > Vicente, can you just confirm that you received the installer I > sent offlist? I'll try to put winsys on PyPI with installers; > just haven't got round to it yes :) > > TJG Tim, I just downloaded it, and am going to install it right away. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 20, 9:36 am, Tim Golden wrote: > > I currently do not have subversion access in my PC. I could try to > > install a free copy of it. But it you could ptovide an installer, it > > certainly would do things easier. Please let me know if it is > > possible. > > Vicente, can you just confirm that you received the installer I > sent offlist? I'll try to put winsys on PyPI with installers; > just haven't got round to it yes :) > > TJG Tim, I just downloaded it, and am going to install it right away. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 20, 4:26 pm, vsoler wrote: > On Aug 20, 9:36 am, Tim Golden wrote: > > > > I currently do not have subversion access in my PC. I could try to > > > install a free copy of it. But it you could ptovide an installer, it > > > certainly would do things easier. Please let me know if it is > > > possible. > > > Vicente, can you just confirm that you received the installer I > > sent offlist? I'll try to put winsys on PyPI with installers; > > just haven't got round to it yes :) > > > TJG > > Tim, > > I just downloaded it, and am going to install it right away. Tim, It works!!! or at least, should I say, it runs!!! wonderful. Now, would it be possible to have a hint/suggestion as to some lines that I should include in my script? I find this exercice very interesting. Thank you for your help. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 20, 5:10 pm, Tim Golden wrote:
> On 20/08/2010 15:49, vsoler wrote:
>
>
>
> > On Aug 20, 4:26 pm, vsoler wrote:
> >> On Aug 20, 9:36 am, Tim Golden wrote:
>
> >>>> I currently do not have subversion access in my PC. I could try to
> >>>> install a free copy of it. But it you could ptovide an installer, it
> >>>> certainly would do things easier. Please let me know if it is
> >>>> possible.
>
> >>> Vicente, can you just confirm that you received the installer I
> >>> sent offlist? I'll try to put winsys on PyPI with installers;
> >>> just haven't got round to it yes :)
>
> >>> TJG
>
> >> Tim,
>
> >> I just downloaded it, and am going to install it right away.
>
> > Tim,
>
> > It works!!! or at least, should I say, it runs!!! wonderful.
>
> > Now, would it be possible to have a hint/suggestion as to some lines
> > that I should include in my script?
>
> Depends what, exactly, you want your script to do :)
>
> The simplest way to get an ad-hoc look at what permissions are applied to
> a file is:
>
>
> import os, sys
> from winsys import fs
>
> #
> # Just using sys.executable as a file I know will exist;
> # obviously you put your own file name in there...
> #
> fs.file (sys.executable).security ().dump ()
>
>
>
> To get that in the more compact but more esoteric MS SDDL format:
>
>
> import os, sys
> from winsys import fs
>
> print (fs.file (sys.executable).security ())
>
>
>
> To decode the permission bit-strings to vaguely meaningful
> names:
>
>
> import os, sys
> from winsys import fs
>
> dacl = fs.file (sys.executable).security ().dacl
> for permission in dacl:
> print (d.trustee, " (Inherited )" if d.inherited else "")
> for name in fs.FILE_ACCESS.names_from_value (d.access):
> print (" ", name)
>
>
>
> TJG
Tim,
in your last piece of code, the definition of "d" is missing. missed
anything when copying?
Vicente Soler
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 20, 5:10 pm, Tim Golden wrote:
> On 20/08/2010 15:49, vsoler wrote:
>
>
>
> > On Aug 20, 4:26 pm, vsoler wrote:
> >> On Aug 20, 9:36 am, Tim Golden wrote:
>
> >>>> I currently do not have subversion access in my PC. I could try to
> >>>> install a free copy of it. But it you could ptovide an installer, it
> >>>> certainly would do things easier. Please let me know if it is
> >>>> possible.
>
> >>> Vicente, can you just confirm that you received the installer I
> >>> sent offlist? I'll try to put winsys on PyPI with installers;
> >>> just haven't got round to it yes :)
>
> >>> TJG
>
> >> Tim,
>
> >> I just downloaded it, and am going to install it right away.
>
> > Tim,
>
> > It works!!! or at least, should I say, it runs!!! wonderful.
>
> > Now, would it be possible to have a hint/suggestion as to some lines
> > that I should include in my script?
>
> Depends what, exactly, you want your script to do :)
>
> The simplest way to get an ad-hoc look at what permissions are applied to
> a file is:
>
>
> import os, sys
> from winsys import fs
>
> #
> # Just using sys.executable as a file I know will exist;
> # obviously you put your own file name in there...
> #
> fs.file (sys.executable).security ().dump ()
>
>
>
> To get that in the more compact but more esoteric MS SDDL format:
>
>
> import os, sys
> from winsys import fs
>
> print (fs.file (sys.executable).security ())
>
>
>
> To decode the permission bit-strings to vaguely meaningful
> names:
>
>
> import os, sys
> from winsys import fs
>
> dacl = fs.file (sys.executable).security ().dacl
> for permission in dacl:
> print (d.trustee, " (Inherited )" if d.inherited else "")
> for name in fs.FILE_ACCESS.names_from_value (d.access):
> print (" ", name)
>
>
>
> TJG
it seems as though the definition of "d" is missing in your last piece
of code
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 20, 7:42 pm, Tim Golden wrote:
> On 20/08/2010 5:10 PM, vsoler wrote:
>
>
>
> > On Aug 20, 5:10 pm, Tim Golden wrote:
> >> To decode the permission bit-strings to vaguely meaningful
> >> names:
>
> >>
> >> import os, sys
> >> from winsys import fs
>
> >> dacl = fs.file (sys.executable).security ().dacl
> >> for permission in dacl:
> >> print (d.trustee, " (Inherited )" if d.inherited else "")
> >> for name in fs.FILE_ACCESS.names_from_value (d.access):
> >> print (" ", name)
>
> >>
>
> >> TJG
>
> > it seems as though the definition of "d" is missing in your last piece
> > of code
>
> Whoops, changed tack mid-thingy. Try:
>
> dacl = ...
> for d in dacl:
> # .. as before
Tim,
I'am testing your library. I am mainly interested in knowing the
access attributes of directories in the local(C:\) or shared unit(W:\)
of my system.
Using your script with 'c:\\' I get an error message saying... 'file
exists but it is a directory' and I cannot go any further.
Of course, the problem is that I am using "fs.file" when I should be
using something different.
Reading the doc I have found that I should be using os.walk(...),
which works, but then I cannot use fs.file
Could you please give me a hint as to what metghod I should be using?
Thank you
Vicente Soler
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 21, 8:10 am, Tim Golden wrote:
> On 20/08/2010 11:54 PM, vsoler wrote:
>
> > I'am testing your library. I am mainly interested in knowing the
> > access attributes of directories in the local(C:\) or shared unit(W:\)
> > of my system.
>
> > Using your script with 'c:\\' I get an error message saying... 'file
> > exists but it is a directory' and I cannot go any further.
>
> > Of course, the problem is that I am using "fs.file" when I should be
> > using something different.
>
> Either use fs.dir (if you know it's a directory) or fs.entry (if it
> could be a file or a directory; the code will dispatch to the right one).
>
> If you only want the directories immediately some directory,
> you could do this:
>
>
> from winsys import fs, security
>
> root = fs.file (sys.executable).path # or fs.dir ("w:/") etc.
> for d in root.dirs (ignore_access_errors=True):
> print (d, "=>", d.security ()) # or whatever
>
>
>
> If you want to walk the tree of directories looking at permissions, then:
>
>
> import os, sys
> from winsys import fs
>
> root = fs.file (sys.executable).path
> for dirpath, _, _ in root.walk ():
> print (dirpath, "=>", dirpath.security ())
>
>
>
> > Reading the doc I have found that I should be using os.walk(...),
> > which works, but then I cannot use fs.file
>
> In fact, even if you did for some reason use os.walk, you can
> easily wrap the returned filenames using fs.entry:
>
>
> import os, sys
> from winsys import fs
>
> root = os.path.dirname (sys.executable)
> for dirpath, filenames, dirnames in os.walk (root):
> print (dirpath, "=>", fs.entry (dirpath).security ())
>
>
>
> TKG
Tim,
I appreciate the time and effort that you are putting in this post.
Personally, I am impressed of the power of python, your winsys
library, and overall, how easy it is to customize the scripting of
one's day to day needs.
I have started testing your first script
from winsys import fs, security
root = fs.dir ("c:/")
for d in root.dirs (ignore_access_errors=True):
print (d, "=>", d.security ())
Howwvwer, I am getting an error:
>>> RESTART
>>>
c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY)
(A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU)
c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)
(A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU)
(A;OICIIOID;SDGXGWGR;;;AU)
c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD)
(A;;FA;;;SY)(A;;FA;;;BA)
c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD)
(A;;FA;;;SY)(A;;FA;;;BA)
c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)
(A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU)
(A;OICIIOID;SDGXGWGR;;;AU)
Traceback (most recent call last):
File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in
print(d, "=>",d.security())
File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in
security
return security.security (self, options=options)
File "C:\Python31\lib\site-packages\winsys\security.py", line 585,
in security
return Security.from_object (str (obj), obj_type, options=options)
File "C:\Python31\lib\site-packages\winsys\security.py", line 475,
in from_object
sd = wrapped (win32security.GetNamedSecurityInfo, obj,
object_type, options)
File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in
_wrapped
raise exception (errno, errctx, errmsg)
winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso
denegado.')
>>>
I am using a system in the Spanish language. As you can see in the
last line, 'Acceso denegado' or 'Access denied' even though the flag
"ignore_access_errors" is set to True.
I am using python 3.1 on Windows 7. What do you think is the origin of
this problem?
Vicente Soler
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 21, 8:10 am, Tim Golden wrote:
> On 20/08/2010 11:54 PM, vsoler wrote:
>
> > I'am testing your library. I am mainly interested in knowing the
> > access attributes of directories in the local(C:\) or shared unit(W:\)
> > of my system.
>
> > Using your script with 'c:\\' I get an error message saying... 'file
> > exists but it is a directory' and I cannot go any further.
>
> > Of course, the problem is that I am using "fs.file" when I should be
> > using something different.
>
> Either use fs.dir (if you know it's a directory) or fs.entry (if it
> could be a file or a directory; the code will dispatch to the right one).
>
> If you only want the directories immediately some directory,
> you could do this:
>
>
> from winsys import fs, security
>
> root = fs.file (sys.executable).path # or fs.dir ("w:/") etc.
> for d in root.dirs (ignore_access_errors=True):
> print (d, "=>", d.security ()) # or whatever
>
>
>
> If you want to walk the tree of directories looking at permissions, then:
>
>
> import os, sys
> from winsys import fs
>
> root = fs.file (sys.executable).path
> for dirpath, _, _ in root.walk ():
> print (dirpath, "=>", dirpath.security ())
>
>
>
> > Reading the doc I have found that I should be using os.walk(...),
> > which works, but then I cannot use fs.file
>
> In fact, even if you did for some reason use os.walk, you can
> easily wrap the returned filenames using fs.entry:
>
>
> import os, sys
> from winsys import fs
>
> root = os.path.dirname (sys.executable)
> for dirpath, filenames, dirnames in os.walk (root):
> print (dirpath, "=>", fs.entry (dirpath).security ())
>
>
>
> TKG
Tim,
I appreciate the time and effort that you are putting in this post.
Personally, I am impressed of the power of python, your winsys
library, and overall, how easy it is to customize the scripting of
one's day to day needs.
I have started testing your first script
from winsys import fs, security
root = fs.dir ("c:/")
for d in root.dirs (ignore_access_errors=True):
print (d, "=>", d.security ())
Howwvwer, I am getting an error:
>>> RESTART
>>>
c:\$recycle.bin\ => O:BAD:PAI(A;;FA;;;BA)(A;OICIIO;GA;;;BA)(A;;FA;;;SY)
(A;OICIIO;GA;;;SY)(A;;0x1201ad;;;BU)
c:\aeat\ => O:BAD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)
(A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU)
(A;OICIIOID;SDGXGWGR;;;AU)
c:\archivos de programa\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD)
(A;;FA;;;SY)(A;;FA;;;BA)
c:\documents and settings\ => O:SYD:PAI(D;;CC;;;WD)(A;;0x1200a9;;;WD)
(A;;FA;;;SY)(A;;FA;;;BA)
c:\hp\ => O:SYD:AI(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)
(A;OICIIOID;GA;;;SY)(A;OICIID;0x1200a9;;;BU)(A;ID;0x1301bf;;;AU)
(A;OICIIOID;SDGXGWGR;;;AU)
Traceback (most recent call last):
File "C:/Users/Vicente/Documents/VS/Python/test6.py", line 5, in
print(d, "=>",d.security())
File "C:\Python31\lib\site-packages\winsys\fs.py", line 1044, in
security
return security.security (self, options=options)
File "C:\Python31\lib\site-packages\winsys\security.py", line 585,
in security
return Security.from_object (str (obj), obj_type, options=options)
File "C:\Python31\lib\site-packages\winsys\security.py", line 475,
in from_object
sd = wrapped (win32security.GetNamedSecurityInfo, obj,
object_type, options)
File "C:\Python31\lib\site-packages\winsys\exc.py", line 55, in
_wrapped
raise exception (errno, errctx, errmsg)
winsys.security.x_security: (5, 'GetNamedSecurityInfo', 'Acceso
denegado.')
>>>
I am using a system in the Spanish language. As you can see in the
last line, 'Acceso denegado' or 'Access denied' even though the flag
"ignore_access_errors" is set to True.
I am using python 3.1 on Windows 7. What do you think is the origin of
this problem?
Vicente Soler
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading the access attributes of directories in Windows
On Aug 21, 8:10 am, Tim Golden wrote:
> On 20/08/2010 11:54 PM, vsoler wrote:
>
> > I'am testing your library. I am mainly interested in knowing the
> > access attributes of directories in the local(C:\) or shared unit(W:\)
> > of my system.
>
> > Using your script with 'c:\\' I get an error message saying... 'file
> > exists but it is a directory' and I cannot go any further.
>
> > Of course, the problem is that I am using "fs.file" when I should be
> > using something different.
>
> Either use fs.dir (if you know it's a directory) or fs.entry (if it
> could be a file or a directory; the code will dispatch to the right one).
>
> If you only want the directories immediately some directory,
> you could do this:
>
>
> from winsys import fs, security
>
> root = fs.file (sys.executable).path # or fs.dir ("w:/") etc.
> for d in root.dirs (ignore_access_errors=True):
> print (d, "=>", d.security ()) # or whatever
>
>
>
> If you want to walk the tree of directories looking at permissions, then:
>
>
> import os, sys
> from winsys import fs
>
> root = fs.file (sys.executable).path
> for dirpath, _, _ in root.walk ():
> print (dirpath, "=>", dirpath.security ())
>
>
>
> > Reading the doc I have found that I should be using os.walk(...),
> > which works, but then I cannot use fs.file
>
> In fact, even if you did for some reason use os.walk, you can
> easily wrap the returned filenames using fs.entry:
>
>
> import os, sys
> from winsys import fs
>
> root = os.path.dirname (sys.executable)
> for dirpath, filenames, dirnames in os.walk (root):
> print (dirpath, "=>", fs.entry (dirpath).security ())
>
>
>
> TKG
Tim,
One of your scripts still does not work on my system:
==> If you want to walk the tree of directories looking at
permissions, then:
import os, sys
from winsys import fs
root = fs.file (sys.executable).path
for dirpath, _, _ in root.walk ():
print (dirpath, "=>", dirpath.security ())
However, I get the following error:
Traceback (most recent call last):
File "C:/Local/test4.py", line 5, in
root = fs.file (r'W:\FRIB\ELPR\$DATA\DPT-FINANZAS').path
File "C:\Program Files\Python31\lib\site-packages\winsys\fs.py",
line 1775, in file
raise x_fs (None, "file", "%s exists but is a directory" %
filepath)
winsys.fs.x_fs: (None, 'file', 'W:\\FRIB\\ELPR\\$DATA\\DPT-FINANZAS
exists but is a directory')
That is, I am interested in looking for directories, but the problem
is that the path is a directory.
I'm sure there must be some way to get around this problem.
Thank you
Vicente Soler
--
http://mail.python.org/mailman/listinfo/python-list
Proper set-up for a co-existant python 2.6 & 3.1 installation
I started learning python with ver 2.6. Then I switched to 3.1 after uninstalling the previous version. Now I find that many of the code snippets that I would need are written for py 2.6. Sometimes the automatic converter 2to3 doesn't help, because it is not able to complete its objective and request manual "tuning" from the user. This is to tell you that I would like to have both versions running on my PC. I am using Windows 7 at home, and Windows Vista in the office. Right now, the two versions are installed on the PC I have at home. If I go to the directory C:\python26 or C:\python31 and I type "python", the correct version of python is launched. I need the pywin32 extensions in either case. I was about to feel happy that everything worked when I found that I cannot change the file associations. If I want to work with py 3.1, I want that a double click on a *.py file launches python 3.1, and not 2.6. On the other hand, when I pan to work with py 2.6 I want that a double click on a*.py file launches python 3.1. I keep source files (*.py) for either version in different directories. I tried to change file associations, first manually, in a CMD window. But the system was responding "access denied" even when I used an Administrator account (I was using FTYPE python.file="C: \Python26\python.exe" "%1" %*). So I directed my efforts towards the Control Panel. But here I got lost. I am not able to find the python file associations (I can find others, but not python's). Perhaps I am focussing my efforts in the wrong direction, but I am not aware of any alternative one. Perhaps you can help me. Thank you Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Proper set-up for a co-existant python 2.6 & 3.1 installation
On 24 ago, 00:55, "Martin v. Loewis" wrote: > > I tried to change file associations, first manually, in a CMD window. > > But the system was responding "access denied" even when I used an > > Administrator account (I was using FTYPE python.file="C: > > \Python26\python.exe" "%1" %*). > > That works, in principle. Put that command into py26.bat, then, in > Explorer, Run As Administrator. Make sure to double-escape the percent > signs. > > Alternatively, you can also write a program that writes to > HKEY_CURRENT_USER; that would take precedence over HKEY_LOCAL_MACHINE. > > Regards, > Martin When I am logged-in in a session as an administrator, the BAT file on the Desktop, and I double-click on it, it does not work. However, if instead of double-clicking on the BAT file, I enter the Explorer and I run the BAT file as administrator, then something seems to start working. Excellent! When you say to double-escape the percent signs, do you mean that in my BAT file I should write... FTYPE python.file="C:\Python26\python.exe" "%%1" %%* and the inverted commas around %%*, are they not necessary? Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Proper set-up for a co-existant python 2.6 & 3.1 installation
On Aug 24, 1:33 am, "Martin v. Loewis" wrote: > > When I am logged-in in a session as an administrator, the BAT file on > > the Desktop, and I double-click on it, it does not work. > > This is not what I meant. Instead, right-click on the BAT file, > and select "run as administrator". > > > When you say to double-escape the percent signs, do you mean that in > > my BAT file I should write... > > > FTYPE python.file="C:\Python26\python.exe" "%%1" %%* > > > and the inverted commas around %%*, are they not necessary? > > No, I don't think so. > > Regards, > Martin Martin (or anybody else), The problem with FTYPE is solved. However, after having switched to py 3.1 with the help of the BAT script (which only changes FTYPE) I have another problem. (Just for reference, here is my batch file) @ECHO OFF ECHO ECHO Cambia a Python 3.1 ECHO ECHO * ECHO FTYPES: ECHO * ECHO .py=Python.File ECHO .pyc=Python.CompiledFile ECHO .pyo=Python.CompiledFile ECHO .pys=pysFile ECHO .pyw=Python.NoConFile ECHO * ECHO ECHO * FTYPE python.file="C:\Python31\python.exe" "%%1" %%* FTYPE python.compiledfile="C:\Python31\python.exe" "%%1" %%* FTYPE python.NoConFile="C:\Python31\pythonw.exe" "%%1" %%* ECHO * Pause @ECHO ON The problem is that, if I am on top of a .py file, and, with the mouse, I click on the right button, then I click on "Edit with IDLE", I get the 2.6 system, not the 3.1 one (which was supposed to be the correct one after the change). My question is: are there any other changes that I should do in order to fully switch from one version to another? Thank you in advance. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Question on the "csv" library
I am trying to read a csv file generated by excel.
Although I succeed in reading the file, the format that I get is not
suitable for me.
I've done:
>>> import csv
>>> spamReader = csv.reader(open('C:\\abc.csv', 'r'))
>>> print spamReader
<_csv.reader object at 0x01022E70>
>>> for row in spamReader:
print row
['codigo;nombre;cantidad']
['a;qwe;1']
['b;asd;2']
['c;zxc;3']
My questions are:
1- Why using "print spamReader" I cannot see the data?
I expected to see a list of lists, a kind of a matrix, but I get
nothing
2- Why are the rows in a single string?
I expected a list of fields that, when text, would be delimited by
"
To tell the truth, the file generated by excel does not contain the
strings delimited by ". Isn't it weird?
3- Is there anything I can do to have my data in a list of lists
structure? would another kind of data suit better my needs?
Thank you for your help
Vicente Soler
--
http://mail.python.org/mailman/listinfo/python-list
Re: Question on the "csv" library
On Aug 27, 9:42 pm, Andreas Waldenburger wrote: > On Thu, 27 Aug 2009 21:36:28 +0200 Andreas Waldenburger > > wrote: > > [snip] > > > Might I humbly suggest > > > >>> sheet = list(spamReader) # ? > > Oh, and while I'm humbly suggesting: > > spam_reader instead of spamReader or SpamReader or SpamrEadeR or > suchlike. Caps are "reserved" for classes. > > Not a necessity, of course. But it's the dialect around these parts. > > /W > > -- > INVALID? DE! Thank you for your answers. Let me however make some comments: 1- the csv file was generated with Excel 2007; no prompts for what the separator should be; Excel has used ";" by default, without asking anything 2- about capitalisation, I used the var "spamReader" because I just copy/pasted from the official python site: http://docs.python.org/library/csv.html 3- when I try >>> sheet = [row for row in spamReader] >>> print sheet [] all I get is an empty list; something seems not to be working properly Same result list: I get an empty list sheet = list(spamReader) Thank you again for your help, which is highly appreciated. Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on the "csv" library
On Aug 28, 5:43 pm, Steven Rumbalski
wrote:
> On Aug 27, 3:06 pm, vsoler wrote:
>
>
>
> > I am trying to read a csv file generated by excel.
>
> > Although I succeed in reading the file, the format that I get is not
> > suitable for me.
>
> > I've done:
>
> > >>> import csv
> > >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'))
> > >>> print spamReader
>
> > <_csv.reader object at 0x01022E70>
>
> > >>> for row in spamReader:
>
> > print row
>
> > ['codigo;nombre;cantidad']
> > ['a;qwe;1']
> > ['b;asd;2']
> > ['c;zxc;3']
>
> > My questions are:
>
> > 1- Why using "print spamReader" I cannot see the data?
> > I expected to see a list of lists, a kind of a matrix, but I get
> > nothing
>
> > 2- Why are the rows in a single string?
> > I expected a list of fields that, when text, would be delimited by
> > "
> > To tell the truth, the file generated by excel does not contain the
> > strings delimited by ". Isn't it weird?
>
> > 3- Is there anything I can do to have my data in a list of lists
> > structure? would another kind of data suit better my needs?
>
> > Thank you for your help
>
> > Vicente Soler
>
> the csv module can handle any delimiter.
>
> change this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'))
> to this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'),
> delimiter=';')
>
> hope this helps,
> Steven Rumbalski
Thank you very much for all your comments. After reading them I can
conclude that:
1- the CSV format is not standardized; each piece of software uses it
differently
2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";"
comes from my regional Spanish settings
3- Excel does not even put quotes around litteral texts, not even when
the text contains a blank
But, perhaps, there is no standard alternative to CSV !!!
--
http://mail.python.org/mailman/listinfo/python-list
Colors on IDLE
Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors on IDLE
On Aug 28, 8:58 pm, vsoler wrote: > Everything that I see in IDLE is in black. > > I have tried to add colors, without success. > > I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic Couldn't finish writing... sorry --- Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic However, everything remains black. Any help is highly appreciated Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors on IDLE
On Aug 28, 9:55 pm, Chris Rebert wrote: > On Fri, Aug 28, 2009 at 12:00 PM, vsoler wrote: > > On Aug 28, 8:58 pm, vsoler wrote: > >> Everything that I see in IDLE is in black. > > >> I have tried to add colors, without success. > > >> I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic > > > Couldn't finish writing... sorry > > --- > > > Everything that I see in IDLE is in black. > > > I have tried to add colors, without success. > > > I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic > > > However, everything remains black. Any help is highly appreciated > > What OS are you on? > > - Chris Windows XP -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors on IDLE
On Aug 29, 1:27 am, r wrote: > Have you tried saving the files as MYScriptName.py? notice the py > extension, very important ;) That was it!!! I see the colors again. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Colors on IDLE
On Aug 29, 1:34 pm, Thorsten Kampe wrote: > * vsoler (Sat, 29 Aug 2009 04:01:46 -0700 (PDT)) > > > On Aug 29, 1:27 am, r wrote: > > > Have you tried saving the files as MYScriptName.py? notice the py > > > extension, very important ;) > > > That was it!!! > > > I see the colors again. Thank you. > > I suggest you start using familiar technical terms. Like "syntax > highlighting" instead of "see colours". That would increase the number > of useful answers you get - at least it will stop people from thinking > you talk about controlled substances. > > Thorsten I'll keep it in mind for next time. Thank you Vicente Soler -- http://mail.python.org/mailman/listinfo/python-list
Efficient way to sum a product of numbers...
Hi,
After simplifying my problem, I can say that I want to get the sum of
the product of two culumns:
Say
m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]]
r={'a':4, 'b':5, 'c':6}
What I need is the calculation
1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26
That is, for each row list in variable 'm' look for its first element
in variable 'r' and multiply the value found by the second element in
row 'm'. After that, sum all the products.
What's an efficient way to do it? I have thousands of these
calculations to make on a big data file.
Thank you.
--
http://mail.python.org/mailman/listinfo/python-list
