Re: Is there any way to access attributes from an imported module?

2011-10-02 Thread Steven D'Aprano
Andrew Berg wrote:

> I'm not sure the subject's wording is the best, but I'll try to explain.
> I have a main script that imports several modules and I need to be able
> to call methods from a class instance inside that main script from a
> module. Currently, functions can be defined to access the methods, but
> such functions can only be called via commands sent to the main script
> (it's an IRC bot, and commands are sent via IRC). What I want to do is
> call those methods without sending commands (I want to send an IRC
> message from an except clause).


Have I missed something? Why can't you just import the module and call the
methods like you would for any other module and class?

import module
instance = module.Some_Class()
result = instance.method(some, arguments, may, be, needed)



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


question on installing python 2.7.2 and tcl 8.5.10 on WinXP

2011-10-02 Thread Lynn Oliver
Hello,

I'm having problems building tcl/tk and python on Windows XP so that both are 
installed correctly.

1. ActivePython 2.7.2.5 works fine on my system but may be implicated in recent 
R6034 runtime errors from users.

2. Python.org 2.7.2 msi binaries install fine, but produce a "tcl wasn't 
installed correctly" runtime error from pyinstaller builds.  

3. I built Python.org 2.7.2 sources using MSVC++ 2008 Express with a lot of 
manual work for the subprocess wrappers. The buildbot tools, which should more 
or less automate that process, did not work for me.

4. I can build tcl/tk 8.5.10 using MinGW/Msys.

5. When I built the tkinter component, I placed the build of tcl/tk where it 
was expected by the build scripts, and VC++ reported that the build was 
successful.  However, if I start python.exe from the build directory, I can't 
import Tkinter (or tkinter).

I feel like I must be missing some basic understanding of how and where things 
are installed; having completed the builds I still don't know how to install 
the resulting files into the correct directories.  

Any suggestions?  

Thanks for your help,
Lynn-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to access attributes from an imported module?

2011-10-02 Thread Andrew Berg
On 2011.10.02 01:55 AM, Steven D'Aprano wrote:
> Have I missed something? Why can't you just import the module and call the
> methods like you would for any other module and class?
> 
> import module
> instance = module.Some_Class()
> result = instance.method(some, arguments, may, be, needed)
I need to affect the instance created in the main script; creating a new
instance would be pointless (and AFAICT would result in the interpreter
hitting a recursion limit since the module is imported during creation
of the instance).

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to access attributes from an imported module?

2011-10-02 Thread Andrew Berg
On 2011.10.02 02:11 AM, Gary Herron wrote:
> You may be able to do the simplest thing:  If a module wants to call 
> something form the main module (or main script as you call it) just try 
> importing that main script and call whatever it is you want.  This 
> results in a circular set of imports, but Python can often deal with 
> those without trouble.  (Not always, so circular imports are best 
> avoided in general, but .. try it and see.)
It doesn't work. I get an AttributeError any time I try to access the
class instance from the sub-module. Even moving the load() call outside
__init__() doesn't change this.

> If there is code in the main script (module) that needs to be called 
> form elsewhere, take it out of the main module and put it in a separate 
> module.  Then import that new module both in the main script, and the 
> various sub-modules.  This is cleaner than the circular imports in the 
> previous solution.
I need to affect a specific instance which imports the sub-modules.



I worded the subject line wrong (and I've no clue how to word it now).
This is quite hard to explain, and I don't think it's easy to understand
without really examining the code (I don't even fully understand it).
More ideas are certainly welcome, but I think I'll have to ask the
developer (who has only been somewhat active lately).

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to access attributes from an imported module?

2011-10-02 Thread Steven D'Aprano
Andrew Berg wrote:

> On 2011.10.02 01:55 AM, Steven D'Aprano wrote:
>> Have I missed something? Why can't you just import the module and call
>> the methods like you would for any other module and class?
>> 
>> import module
>> instance = module.Some_Class()
>> result = instance.method(some, arguments, may, be, needed)
>
> I need to affect the instance created in the main script; 

Then call the methods on the instance created in the main script. I'm still
failing to see your problem.



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: executing arbitrary statements

2011-10-02 Thread Jonathan Hartley
On Saturday, October 1, 2011 8:06:43 AM UTC+1, Chris Rebert wrote:
> On Fri, Sep 30, 2011 at 11:31 PM, Jason Swails  wrote:
> > I'm probably missing something pretty obvious, but I was wondering if there
> > was a way of executing an arbitrary line of code somehow (such as a line of
> > code based on user-input).  There's the obvious use of "eval" that will
> > evaluate a function call, but that doesn't allow all things.
> 
> > Because write is a function eval works fine for it.  But since print isn't
> > (2.7), it throws a syntax error.  Likewise, variable assignments aren't
> > allowed either as they are also not functions and lack a return value:
> 
> 
> Use the `exec` statement, which is capable of executing statements (as
> opposed to just expressions):
> http://docs.python.org/reference/simple_stmts.html#the-exec-statement
> 
> > What I'm more or less looking to do is present a (limited) form of an
> > interpreter inside the application I'm writing for the advanced user.
> >
> > I'm also interested to hear if this is a particularly bad idea for any
> > reason,
> 
> It's potentially rather hacky and ad-hoc to effectively directly
> inject arbitrary statements at certain points in your code.
> 
> Assuming you were to trust the user-provided code, callbacks/hooks or
> plugin modules are typically much cleaner ways to integrate custom
> code from the user.
> 
> Depending on your particular use case, the `cmd` module might also be
> a workable alternative:
> http://docs.python.org/library/cmd.html
> 
> > and if there are security issues involved with allowing users to
> > execute their own code inside my program (keeping in mind that some people
> > may "donate" their scripts to others that may run them as black boxes).
> 
> It is *very much* a security issue!
> 
> > Is
> > it enough to disallow import statements, thereby not giving direct access to
> > the sys and os modules?
> 
> Not by a long shot! There are a bunch of known tricks that exploit
> introspection to circumvent such restrictions.
> Secure execution of untrusted Python code is a difficult problem. Some
> have accomplished it to a degree, but typically only by modifying the
> interpreter itself or imposing relatively onerous restrictions on the
> untrusted code.
> 
> > I know more or less what I want to do, but I'd also
> > appreciate any experienced input/advice/suggestions.
> 
> I additionally came across this in researching my reply:
> http://pypi.python.org/pypi/RestrictedPython/
> Apparently the speed of execution leaves something to be desired, but
> the package /supposedly/ works well otherwise.
> 
> Cheers,
> Chris
> --
> http://rebertia.com


I (and many others) entirely avoid using 'eval' in all my code for many years, 
based on the security concerns that Chris rightly highlights. It's worth noting 
though, that RaymondH's talks last year on some valid uses of 'eval' and 'exec' 
have opened my eyes to it somewhat. In summary, while it's dangerous to execute 
user-submitted code, there are no security risks associated with executing code 
generated by your own program. It takes a while to see how this might be 
useful, if (like me) you're not used to thinking about it.

Raymond's premier example was his implementation of namedtuple:
(see http://hg.python.org/cpython/file/default/Lib/collections/__init__.py)
This defines a string, the contents of which is a class definition, with some 
string formatting markers in it. These are replaced with known values on 
invocation of the namedtuple factory function, which then exec's the 
class-definition string and returns the resulting new type.

This results in an implementation that is both simpler and faster than trying 
to simply write a general-purpose class that does at runtime all the things 
that 'namedtuple' does.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: executing arbitrary statements

2011-10-02 Thread Steven D'Aprano
Jonathan Hartley wrote:

> I (and many others) entirely avoid using 'eval' in all my code for many
> years, based on the security concerns that Chris rightly highlights. It's
> worth noting though, that RaymondH's talks last year on some valid uses of
> 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while
> it's dangerous to execute user-submitted code, there are no security risks
> associated with executing code generated by your own program.

That's not strictly true. If you look at the code for namedtuple, you will
see that Raymond actually spends significant effort to sanitise the input
to namedtuple. Right at the top of the class is this comment:

# Parse and validate the field names.  Validation serves two purposes,
# generating informative error messages and preventing template injection
attacks.

So even something like namedtuple needs to take care of security risks.

In a more general sense, "security" does not necessarily mean security
against outsiders. Sometimes the threat you're defending from is an
insider, or even yourself: for example, there are various utility programs
designed to prevent you from emailing while drunk (I know people who should
use them!), *many* security protocols designed to prevent a single rogue
member of an organisation from doing harm (e.g. it takes at least two
people to launch nuclear warheads), etc. This is why (for example) on
Linux, the rm command defaults to interactive use when given as root. If
you've ever typed rm -r * in the wrong directory (especially the root
directory) you'll understand that sometimes the worst threat is yourself.



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Chaos Theory [was Re: Benefit and belief]

2011-10-02 Thread rusi
On Oct 2, 8:03 am, Steven D'Aprano  wrote:
> By the way, who removed the OT label from the subject line? Please don't
> unless it actually comes back on topic.
>
> DevPlayer wrote:
> > I still assert that contradiction is caused by narrow perspective.
>
> There's no doubt that some *apparent* contradictions are caused by lack of
> correct information. But:
>
> N is an even number;
> N (the same N, for avoidance of doubt) is an odd number
>
> is still a contradiction, no matter how you look at it.

DevPlayer is probably talking of 'synthetic/a posteriori' statements
You're changing it to 'analytic/a priori' (like the OT subject line
)
(see http://en.wikipedia.org/wiki/Analytic%E2%80%93synthetic_distinction#Kant
)
-- 
http://mail.python.org/mailman/listinfo/python-list


Replacing spreadsheets by Python and the browser

2011-10-02 Thread markolopa
Hello,

Could you please recommend me a Python tool that could help me to get
rid of the messy information and scripts I have in spreadsheets?

Spreadsheets are great for having simple things done quickly. But as
the needs grow their limitations can be quite frustrating. I would
like to use the browser to edit information that for the moment I
store in spreadsheets.

I believe that the perfect tool for me would be that a combination a
table editing tool and a tree navigation tool. I would like to
navigate in a tree, expanding and collapsing nodes. The leaf nodes
would then be tables with some editable columns.

A good table editing tool (without the tree navigation) would already
be very helpful.

Examples of information I would store in such a tree/table system
(which are now in spreasheets):
- My dvd, avi collection: The tree would be the directory tree of the
file system where I store my movies. For each directory containing the
avis or the dvds there would be a table with one movie by row and
several editable columns: the file name, the genre, the year, whether
I have seen it or not, comments, etc.
. The same thing for mp3.
- My family budget. The tree would be the account tree, the rows in
the table would be the deposits and withdrwals. This is actually my
most important need. I don't find gnucash flexible enough for my
needs.  Beancount (http://furius.ca/beancount/) has a great html
output, but I would like to use the browser also for input.

I am very comfortable with Python, but I don't know much about web
framewords and javascript interfaces. I am ready to learn anything
that could help me to do the desired tasks quickly, without having to
code a web application from scratch. Is javascript the way to go? In
this case is there a Python lib can I use on the server side? Could a
tool like django be helpful? Pyjamas? Both a single machine or a
client-server architecture are fine for me.

Thanks a lot in advance for all suggestion,
Marko
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing spreadsheets by Python and the browser

2011-10-02 Thread Andrea Crotti

On 10/02/2011 06:36 PM, markolopa wrote:

Hello,

Could you please recommend me a Python tool that could help me to get
rid of the messy information and scripts I have in spreadsheets?

Spreadsheets are great for having simple things done quickly. But as
the needs grow their limitations can be quite frustrating. I would
like to use the browser to edit information that for the moment I
store in spreadsheets.

I believe that the perfect tool for me would be that a combination a
table editing tool and a tree navigation tool. I would like to
navigate in a tree, expanding and collapsing nodes. The leaf nodes
would then be tables with some editable columns.

A good table editing tool (without the tree navigation) would already
be very helpful.

Examples of information I would store in such a tree/table system
(which are now in spreasheets):
- My dvd, avi collection: The tree would be the directory tree of the
file system where I store my movies. For each directory containing the
avis or the dvds there would be a table with one movie by row and
several editable columns: the file name, the genre, the year, whether
I have seen it or not, comments, etc.
. The same thing for mp3.
- My family budget. The tree would be the account tree, the rows in
the table would be the deposits and withdrwals. This is actually my
most important need. I don't find gnucash flexible enough for my
needs.  Beancount (http://furius.ca/beancount/) has a great html
output, but I would like to use the browser also for input.

I am very comfortable with Python, but I don't know much about web
framewords and javascript interfaces. I am ready to learn anything
that could help me to do the desired tasks quickly, without having to
code a web application from scratch. Is javascript the way to go? In
this case is there a Python lib can I use on the server side? Could a
tool like django be helpful? Pyjamas? Both a single machine or a
client-server architecture are fine for me.

Thanks a lot in advance for all suggestion,
Marko



Well my answer is not really python-related, but one tool that really 
changed my life is orgmode

http://orgmode.org/

It does almost everything you ask and a 1000 other things.
If you want to go with a python project, in general you should probably 
need a lot of javascript
to have something which is nice and easy to use, and yes something like 
django would work.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing spreadsheets by Python and the browser

2011-10-02 Thread rusi
On Oct 2, 10:36 pm, markolopa  wrote:
> Hello,
>
> Could you please recommend me a Python tool that could help me to get
> rid of the messy information and scripts I have in spreadsheets?
>
> Spreadsheets are great for having simple things done quickly. But as
> the needs grow their limitations can be quite frustrating. I would
> like to use the browser to edit information that for the moment I
> store in spreadsheets.
>
> I believe that the perfect tool for me would be that a combination a
> table editing tool and a tree navigation tool. I would like to
> navigate in a tree, expanding and collapsing nodes. The leaf nodes
> would then be tables with some editable columns.
>
> A good table editing tool (without the tree navigation) would already
> be very helpful.
>
> Examples of information I would store in such a tree/table system
> (which are now in spreasheets):
> - My dvd, avi collection: The tree would be the directory tree of the
> file system where I store my movies. For each directory containing the
> avis or the dvds there would be a table with one movie by row and
> several editable columns: the file name, the genre, the year, whether
> I have seen it or not, comments, etc.
> . The same thing for mp3.
> - My family budget. The tree would be the account tree, the rows in
> the table would be the deposits and withdrwals. This is actually my
> most important need. I don't find gnucash flexible enough for my
> needs.  Beancount (http://furius.ca/beancount/) has a great html
> output, but I would like to use the browser also for input.
>
> I am very comfortable with Python, but I don't know much about web
> framewords and javascript interfaces. I am ready to learn anything
> that could help me to do the desired tasks quickly, without having to
> code a web application from scratch. Is javascript the way to go? In
> this case is there a Python lib can I use on the server side? Could a
> tool like django be helpful? Pyjamas? Both a single machine or a
> client-server architecture are fine for me.
>
> Thanks a lot in advance for all suggestion,
> Marko

May not be what you are asking for but you may want to look at
orgmode:

http://orgmode.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Adding new keywords to Python interpreter

2011-10-02 Thread Yaşar Arabacı
Hi people,

Nowadays, I am trying to explore python source. I added a new keyword,
essentially doing same thing as 'continue' keyword to the interpreter,
mostly by following instructions in PEP 306. If anyone interested here is
the video about how I did it:  http://www.youtube.com/watch?v=Ww7BeIdUbUI notes
in video are in Turkish, but you don't require the notes much, as they don't
mention any crucial point.

By the way, I am not saying this is the best, or even right way to do it. I
am just sharing what I have done.

Have a nice day :)
-- 
http://yasar.serveblog.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing spreadsheets by Python and the browser

2011-10-02 Thread rantingrick
On Oct 2, 12:36 pm, markolopa  wrote:

> Examples of information I would store in such a tree/table system
> (which are now in spreasheets):
> - My dvd, avi collection: The tree would be the directory tree of the
> file system where I store my movies. For each directory containing the
> avis or the dvds there would be a table with one movie by row and
> several editable columns: the file name, the genre, the year, whether
> I have seen it or not, comments, etc.
> . The same thing for mp3.
> - My family budget. The tree would be the account tree, the rows in
> the table would be the deposits and withdrwals. This is actually my
> most important need. I don't find gnucash flexible enough for my
> needs.  Beancount (http://furius.ca/beancount/) has a great html
> output, but I would like to use the browser also for input.

Is there any reason why you could not use the advanced widgets in
WxPython? You never said whether this MUST BE a web application. If
GUI is okay then check out wxListCtrl and wxTreeCtrl. All you need to
do is write a little control code and voila.

http://www.wxpython.org/onlinedocs.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing spreadsheets by Python and the browser

2011-10-02 Thread python
Check out ResolverOne
http://www.resolversystems.com

Malcolm
-- 
http://mail.python.org/mailman/listinfo/python-list


Change import order with *.pth files

2011-10-02 Thread Andrea Gavana
Hi All,

my apologies if this is a dumb question, but I couldn't find a solution
 - possibly because I am not sure how to state my problem in a short
sentence.

Let's say I am using a package called "blah", and this package is already
installed on site-packages (and I need it to be there) with a name
"blah-1.2-win". In the site-packages folder, there is a pth file called
"blah.pth" which contains this line:

blah-1.2-win

To redirect Python to the correct folder when I type "import blah". Anyway,
now I am developing another version of this package and it's called
"blah-2.0-win", and it sits on my computer into a different folder (not on
site-packages, on an entire different drive in reality). How can I tell
Python *not* to use the version inside site-packages but to use the other
one in my development folder (without touching the pth file in
site-packages, of course)?

I have tried fiddling with sys.path and to create a local (in my development
folder) pth file, to no avail. I hope I have been able to explain my problem
clearly... This is on Windows, Python 2.5 to 2.7.

Thank you in advance for your suggestions.

Andrea.

"Imagination Is The Only Weapon In The War Against Reality."
http://xoomer.alice.it/infinity77/
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] Re: Chaos Theory [was Re: Benefit and belief]

2011-10-02 Thread Steven D'Aprano
On Sun, 02 Oct 2011 08:03:07 -0700, rusi wrote:

> On Oct 2, 8:03 am, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>> By the way, who removed the OT label from the subject line? Please
>> don't unless it actually comes back on topic.
>>
>> DevPlayer wrote:
>> > I still assert that contradiction is caused by narrow perspective.
>>
>> There's no doubt that some *apparent* contradictions are caused by lack
>> of correct information. But:
>>
>> N is an even number;
>> N (the same N, for avoidance of doubt) is an odd number
>>
>> is still a contradiction, no matter how you look at it.
> 
> DevPlayer is probably talking of 'synthetic/a posteriori' statements
> You're changing it to 'analytic/a priori' (like the OT subject line
> )
> (see
> http://en.wikipedia.org/wiki/Analytic%E2%80%93synthetic_distinction#Kant
> )


An interesting link. I knew the Objectivists were nuts, but I really 
didn't appreciate quite how nuts they were until I read Leonard Peikoff's 
criticism of Kant. Not that I necessary agree with Kant, but the 
Objectivist argument basically boils down to "We would like empirical 
knowledge to be 100% certain, but Kant demonstrates that it isn't. 
Therefore he must be wrong."

Or to put it another way:

"I reject your reality and substitute my own."


But in any case, no, I am not merely talking about analytic/a priori 
statements. Here's a synthetic/a priori version:

(a) The sum of odd numbers between 6 and 20 equals 91.
(b) The sum of odd numbers between 6 and 20 equals 93.

and here's a synthetic/a posteriori version:

(c) During the 1936 Olympic Games, the leader of the host nation had a 
full beard.
(d) During the 1936 Olympic Games, the leader of the host nation did not 
have a full beard.

Unlike Kant, I don't think that analytic/a posteriori is contradictory. 
Here is an example:

(e) Combustion is caused by a chemical reaction between an oxidant and 
some other reagent.
(f) Combustion is caused by the release of phlogiston from materials.


In all cases, we can be sure that the contradiction between the pair of 
statements are genuine contradictions and not mere apparent 
contradictions caused by "narrow perspective" or incomplete or erroneous 
knowledge.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Change import order with *.pth files

2011-10-02 Thread Andrea Crotti

On 10/02/2011 10:29 PM, Andrea Gavana wrote:

Hi All,

my apologies if this is a dumb question, but I couldn't find a 
solution  - possibly because I am not sure how to state my problem in 
a short sentence.


Let's say I am using a package called "blah", and this package is 
already installed on site-packages (and I need it to be there) with a 
name "blah-1.2-win". In the site-packages folder, there is a pth file 
called "blah.pth" which contains this line:


blah-1.2-win

To redirect Python to the correct folder when I type "import blah". 
Anyway, now I am developing another version of this package and it's 
called "blah-2.0-win", and it sits on my computer into a different 
folder (not on site-packages, on an entire different drive in 
reality). How can I tell Python *not* to use the version inside 
site-packages but to use the other one in my development folder 
(without touching the pth file in site-packages, of course)?


I have tried fiddling with sys.path and to create a local (in my 
development folder) pth file, to no avail. I hope I have been able to 
explain my problem clearly... This is on Windows, Python 2.5 to 2.7.


Thank you in advance for your suggestions.

Andrea.


Well messing up with the pth file is not a very good idea in general, 
since it's thought to be manipulated by distutils, not by hand.


The best way to solve your problem is to use virtualenv or something 
similar, check it out...


--
http://mail.python.org/mailman/listinfo/python-list


getattr and method name

2011-10-02 Thread Kevin Walzer
I'm seeing a very odd error in an application I'm developing using 
Python 2.7.2, on Mac OS 10.7.


This application uses a wrapper method to look up other method names via 
getattr and then call those methods. I have not previously had an issue 
with this name, but for some reason this functionality no longer works 
as expected.


Here is the relevant code:

#run command with root privileges
def runCommand(self, cmd, *args):
try:
functionstring = args[2]
callfunction = getattr(self, functionstring.split('.')[1])
self.passtext = self.tk.call('authorize::getAuthPassword')
callfunction()
except:
try:
print cmd
functionstring = cmd.split()[2]
callfunction = getattr(self, functionstring.split('.')[1])
self.passtext = self.tk.call('authorize::getAuthPassword')
callfunction()
except:
raise

I use this approach to call the method named in the "cmd" parameter 
because I also have to look up a password name that is returned by an 
underlying Tk package that I use in my application (that's the reason 
for the 'self.tk.call'). What is happening is when I use the 
"callfunction()" call, instead of the method name being called, a string 
like this is being invoked:


<__main__.phynchronicityApp instance at 0x101b232d8>>


The "scanPackages" method (just to use it as an example) uses Popen to 
call an underlying system tool on the OS. However, when invoked via 
callfunction(), the 'bound method...' string is passed to the OS instead 
as a command! As a result, I get this output from the pipe:


/bin/sh: bound: No such file or directory

I am not sure what in my application is causing this kind of breakage, 
as earlier versions of the app ran fine with similar code on earlier 
versions on the OS. Is this the correct way to structure this kind of 
functionality, or am I better off structuring it some other way?


--Kevin
--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


Advise on using logging.getLogger needed.

2011-10-02 Thread Steven W. Orr
I hope I don't sound like I'm ranting :-(

I have created a module (called xlogging) which sets up logging the way I want
it. I found out that if I set up my logger without a name, then it gets
applied to every logger that is referenced by every module that ever gets
imported.

The problem is that I must call xlogging.getLogger or logging.getLogger in all
other modules using the name of the root logger, and I don't know what that
name is.

I want the name of the root logger to be the name of the running program, so
in my setup, I say

pname = sys.argv[0]
try:
rslash = pname.rindex('/')
except ValueError:
pass
else:
pname = pname[rslash + 1:]

try:
dot_py = pname.rindex('.py')
except ValueError:
pass
else:
pname = pname[0:dot_py]

and then I say

logger = logging.getLogger(pname)

My problem is that I just want the modules that I write, to be able to get the
 named root logger and still be able to refer to possible sub-loggers.

So, let's say I run program foo. At some point in my mail setup, I set the
configuration for the foo logger. I'd like my xlogging module to supply a
getLogger function such that if I don't supply any arguments, it will return
the logger that would normally be returned by logging.getLogger(pname).

Also, part of the reason I'm confused is because foo calls m1 and m2 and they
want to say

logger = xlogging.getLogger(MaybeWithAnArg?)

at the top of their code. This means that the import statement for m1 and m2
are getting the calls to getLogger executed before I get the chance to set
things up.

I am running 2.6, so I don't have access to logging.getChild, but I'm not
clear that I even want that.

My modules are used by multiple programs. Does this mean that I should simply
use __name__ all the time? (That seems inelegant, no?)

If I'm making sense, is there a way to do this?


-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK + MVC

2011-10-02 Thread Emeka
Greg,

Do you have an example where the Controller is connected?

Regards,
EMeka

On Sun, Oct 2, 2011 at 4:40 AM, Gregory Ewing
wrote:

> Alexander Kapps wrote:
>
>  But I think a simple (and quick 'n' dirty) Tk MVC example can look like
>> this:
>>
>
> The Controller doesn't seem to add any value in that example.
> You might as well connect the Model and Views directly to
> each other.
>
> --
> Greg
> --
> http://mail.python.org/**mailman/listinfo/python-list
>



-- 
*Satajanus  Nig. Ltd


*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getattr and method name

2011-10-02 Thread Chris Rebert
On Sun, Oct 2, 2011 at 3:02 PM, Kevin Walzer  wrote:
> I'm seeing a very odd error in an application I'm developing using Python
> 2.7.2, on Mac OS 10.7.
>
> This application uses a wrapper method to look up other method names via
> getattr and then call those methods. I have not previously had an issue with
> this name, but for some reason this functionality no longer works as
> expected.
>
> Here is the relevant code:
>
>    #run command with root privileges
>    def runCommand(self, cmd, *args):
>        try:
>            functionstring = args[2]
>            callfunction = getattr(self, functionstring.split('.')[1])
>            self.passtext = self.tk.call('authorize::getAuthPassword')
>            callfunction()
>        except:
>            try:
>                print cmd
>                functionstring = cmd.split()[2]
>                callfunction = getattr(self, functionstring.split('.')[1])
>                self.passtext = self.tk.call('authorize::getAuthPassword')
>                callfunction()
>            except:
>                raise
>
> I use this approach to call the method named in the "cmd" parameter because
> I also have to look up a password name that is returned by an underlying Tk
> package that I use in my application (that's the reason for the
> 'self.tk.call'). What is happening is when I use the "callfunction()" call,
> instead of the method name being called, a string like this is being
> invoked:
>
>  instance at 0x101b232d8>>

Er, your terminology seems kinda funky. Do you mean to say that
repr(callfunction) results in that string (which is normal and
expected), or that the return value from callfunction() is that string
(which would be rather bizarre)? I would presume the former. [One does
not call/invoke a string; strings aren't callable.]

> The "scanPackages" method (just to use it as an example) uses Popen to call
> an underlying system tool on the OS. However, when invoked via
> callfunction(), the 'bound method...' string is passed to the OS instead as
> a command! As a result, I get this output from the pipe:
>
> /bin/sh: bound: No such file or directory

Either you've elided some important part of the code from your
fragment above, or the problem would seem to lie in scanPackages()
[presumably its Popen() call is screwy]. Please post the code for
scanPackages(), and (if applicable) the full code for runCommand().

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getattr and method name

2011-10-02 Thread Terry Reedy

On 10/2/2011 6:02 PM, Kevin Walzer wrote:

I'm seeing a very odd error in an application I'm developing using
Python 2.7.2, on Mac OS 10.7.

This application uses a wrapper method to look up other method names via
getattr and then call those methods. I have not previously had an issue
with this name, but for some reason this functionality no longer works
as expected.

Here is the relevant code:

#run command with root privileges
def runCommand(self, cmd, *args):
try:
functionstring = args[2]
callfunction = getattr(self, functionstring.split('.')[1])
self.passtext = self.tk.call('authorize::getAuthPassword')
callfunction()
except:
try:
print cmd
functionstring = cmd.split()[2]
callfunction = getattr(self, functionstring.split('.')[1])
self.passtext = self.tk.call('authorize::getAuthPassword')
callfunction()
except:
raise

I use this approach to call the method named in the "cmd" parameter
because I also have to look up a password name that is returned by an
underlying Tk package that I use in my application (that's the reason
for the 'self.tk.call'). What is happening is when I use the
"callfunction()" call, instead of the method name being called, a string
like this is being invoked:

>

The "scanPackages" method (just to use it as an example) uses Popen to
call an underlying system tool on the OS. However, when invoked via
callfunction(), the 'bound method...' string is passed to the OS instead
as a command! As a result, I get this output from the pipe:

/bin/sh: bound: No such file or directory

I am not sure what in my application is causing this kind of breakage,
as earlier versions of the app ran fine with similar code on earlier
versions on the OS. Is this the correct way to structure this kind of
functionality, or am I better off structuring it some other way?


I do not know of any 2.7 changes that would affect such code. Perhaps 
you changed something in the method being invoked (not shown)

.
You did not specify whether you have the problem in the first or second 
try block. I would start with printing the type and value of some to all 
of the variables.


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: TK + MVC

2011-10-02 Thread Alexander Kapps

On 03.10.2011 00:15, Emeka wrote:

Greg,

Do you have an example where the Controller is connected?


What do you mean? In my example, the Controller *is* connected (to 
both the View and the Model.)

--
http://mail.python.org/mailman/listinfo/python-list


Re: TK + MVC

2011-10-02 Thread Alexander Kapps

On 02.10.2011 04:40, Gregory Ewing wrote:

Alexander Kapps wrote:


But I think a simple (and quick 'n' dirty) Tk MVC example can look
like this:


The Controller doesn't seem to add any value in that example.
You might as well connect the Model and Views directly to
each other.



Sure, in that simple example the Controller is just there to show a 
complete MVC pattern with all three parts. There are often examples 
where the View is actually both, the View and the Controller.


That's why I said that I'm not sure if I really understand the MVC 
pattern. There are so many different versions, sometimes strict and 
sometimes less strict, and I think what's the real problem with my 
example is, whether it is really correct to not connect the Model 
and the View directly, but to let the Controller "mediate" between both.

--
http://mail.python.org/mailman/listinfo/python-list


Re: getattr and method name

2011-10-02 Thread Steven D'Aprano
On Sun, 02 Oct 2011 18:02:05 -0400, Kevin Walzer wrote:

> I'm seeing a very odd error in an application I'm developing using
> Python 2.7.2, on Mac OS 10.7.
> 
> This application uses a wrapper method to look up other method names via
> getattr and then call those methods. I have not previously had an issue
> with this name, but for some reason this functionality no longer works
> as expected.
> 
> Here is the relevant code:
> 
>  #run command with root privileges
>  def runCommand(self, cmd, *args):
>  try:
>  functionstring = args[2]
>  callfunction = getattr(self, functionstring.split('.')[1])
>  self.passtext = self.tk.call('authorize::getAuthPassword')
>  callfunction()
>  except:

Bare excepts should almost never be used. I'd say they certainly 
shouldn't be used like this: you can mask coding bugs, user 
KeyboardInterrupts, and other things which shouldn't be masked.

It also obscures the intent of the code. As far as I can see, it appears 
that this method expects to be called like this:

instance.runCommand(cmd, some, arbitrary, number, of, extra, args)

In this case, the method tries to authenticate and then execute some 
command based on "number" (but ignoring all other arguments, including 
cmd); if ANY failure occurs at all, including too few arguments, missing 
dot in the argument, or failed authentication(?), then try again using 
"cmd" instead. I don't understand the intent of this code.


>  try:
>  print cmd
>  functionstring = cmd.split()[2]
>  callfunction = getattr(self, 
>   functionstring.split('.')[1]) 
>  self.passtext = self.tk.call(
>  'authorize::getAuthPassword')
>  callfunction()
>  except:
>  raise

This try block is completely unnecessary. What's the point of catching an 
exception only to immediately raise it again?



> I use this approach to call the method named in the "cmd" parameter
> because I also have to look up a password name that is returned by an
> underlying Tk package that I use in my application (that's the reason
> for the 'self.tk.call'). 

What's a password name? Generally passwords don't have names themselves. 
Do you mean a user or account name?


> What is happening is when I use the
> "callfunction()" call, instead of the method name being called, a string
> like this is being invoked:
> 
>  <__main__.phynchronicityApp instance at 0x101b232d8>>


Are you sure that's meant to be a string? It appears to be an actual 
bound method. What makes you think it is a string? Where is that output 
coming from? 

My *guess* is that this is the output of the "print cmd" line. If so, 
that tells you nothing about the type of cmd. It does however tell you 
that you need to look at what is calling the runCommand method. Why is it 
being called with a method as the command? What should it be called with? 
Given that you call cmd.split()[2], I would expect that cmd should be a 
string with at least three words.

Taking a wild guess, perhaps you should call cmd to get a string which 
then gets split into pieces to get the name of the system tool you are 
expecting:

 
> The "scanPackages" method (just to use it as an example) uses Popen to
> call an underlying system tool on the OS. However, when invoked via
> callfunction(), the 'bound method...' string is passed to the OS instead
> as a command! As a result, I get this output from the pipe:
> 
> /bin/sh: bound: No such file or directory


Or possibly the error is in callfunction. What does it do?

 
> I am not sure what in my application is causing this kind of breakage,
> as earlier versions of the app ran fine with similar code on earlier
> versions on the OS. Is this the correct way to structure this kind of
> functionality, or am I better off structuring it some other way?

Frankly, it looks like a mess. But I don't understand your intention well 
enough to make any recommendations.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to access attributes from an imported module?

2011-10-02 Thread Rhodri James
On Sun, 02 Oct 2011 06:12:05 +0100, Andrew Berg  
 wrote:



I'm not sure the subject's wording is the best, but I'll try to explain.
I have a main script that imports several modules and I need to be able
to call methods from a class instance inside that main script from a
module.


Do you mean that one of the imported modules wishes to use an instance
created in the main script?  If that's the case, you're going to have
to pass the instance to the module somehow, since the module knows
nothing of what if anything has imported it.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: getattr and method name

2011-10-02 Thread Kevin Walzer
Turns out the error was a typo in the actual method being 
called...*faceinhands*


Sorry for the noise.

--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: getattr and method name

2011-10-02 Thread Gary Herron

On 10/02/2011 05:24 PM, Kevin Walzer wrote:
Turns out the error was a typo in the actual method being 
called...*faceinhands*


Sorry for the noise.



But this is a great example of why you should not use a naked except 
clause.   As stated, your code will execute the except clause for *any* 
kind of an error, not just the exception you envisioned when you wrote 
it.If you had written the except clause to catch just the exceptions 
you were interested in, then the exception int a called function would 
have come through that code as in un-handled exception, instead of being 
caught and essentially ignored.


Gary Herron
--
http://mail.python.org/mailman/listinfo/python-list


Re: getattr and method name

2011-10-02 Thread Roy Smith
In article ,
 Gary Herron  wrote:

> On 10/02/2011 05:24 PM, Kevin Walzer wrote:
> > Turns out the error was a typo in the actual method being 
> > called...*faceinhands*
> >
> > Sorry for the noise.
> >
> 
> But this is a great example of why you should not use a naked except 
> clause.   As stated, your code will execute the except clause for *any* 
> kind of an error, not just the exception you envisioned when you wrote 
> it.If you had written the except clause to catch just the exceptions 
> you were interested in, then the exception int a called function would 
> have come through that code as in un-handled exception, instead of being 
> caught and essentially ignored.

And, along those same lines, a couple of bits of generic exception 
advice...

1) Create specific exceptions to describe specific problems.  
FooPackageSocketBindError sure beats IOError when it comes to trying to 
figure out what went wrong.

2) As much as possible, keep your try blocks short.  In the original 
example, we've got:

   try:
 functionstring = args[2]
 callfunction = getattr(self, functionstring.split('.')[1])
 self.passtext = self.tk.call('authorize::getAuthPassword')
 callfunction()

If we caught an IndexError, we would not know if it came from the 
args[2], or the getattr(...)[1], or possibly even from something deep 
down within callfunction().
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Change import order with *.pth files

2011-10-02 Thread rusi
On 10/02/2011 10:29 PM, Andrea Gavana wrote:
> Hi All,

>     my apologies if this is a dumb question, but I couldn't find a
> solution  - possibly because I am not sure how to state my problem in
> a short sentence.

I think this (and such) are important questions and I too await
answers.

It seems that these questions are poorly dealt with in the python docs
probably because the docs try hard to be generic wrt OS and this is an
area where such 'genericity' confuses more than it helps.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to access attributes from an imported module?

2011-10-02 Thread Andrew Berg
I found a way to do it, albeit a very hackish one. Since the class
instance already catches exceptions from the modules it imports, I can
make a custom exception (in a common area for both it and the submodules
to import) for it to catch and have it call its own methods there based
on information stored in the exception. I'm eventually going to redesign
it to be cleaner and more obvious, but for now, this is a nice
quick-and-dirty solution.

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: timedelta is squicking me out

2011-10-02 Thread Chris Rebert
On Sun, Oct 2, 2011 at 7:27 PM, Phlip  wrote:
> has anyone invented a system like R*by's ActiveSupport's 5.years.ago,
> 42.minutes.since ?
>
> (Yes, I'm aware the notation will be different!)

If something involves Python and nontrivial chronology, then
mxDateTime is the go-to library. And indeed, it has a RelativeDateTime
type:
http://www.egenix.com/products/python/mxBase/mxDateTime/doc/#_Toc293683810

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python without a tty

2011-10-02 Thread Steven D'Aprano
On Fri, 30 Sep 2011 21:09:54 +0100, Nobody wrote:

> On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote:
> 
>>> I have a Python script which I would like to test without a tty
>>> attached to the process. I could run it as a cron job, but is there an
>>> easier way?
[...]
> I suspect that the OP just wants e.g.:
> 
>   script.py &>/dev/null <&-
> 
> which will redirect stdout and stderr to /dev/null and close stdin.


No, that's not what I wanted.

I ended up just running the script as a cron job. It was a one-off (well, 
twice actually, since the first time demonstrated a bug in my code) test 
of some code that tries to determine the size of the current terminal. I 
wanted to ensure that it would do the right thing when run without a tty, 
such as from a cron job.

Thanks to everyone who replied.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK + MVC

2011-10-02 Thread Greg Ewing

Emeka wrote:

Greg,

Do you have an example where the Controller is connected?


No, in fact I've never really felt the need for anything
called a Controller in the GUI stuff I've done. I just
have Models and Views. Models hold the data, and Views
display it and handle input.

If you come across a case where a third object seems
justified, then by all means use one. But don't feel
obliged to include one just because it's part of some
official pattern or other.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python without a tty

2011-10-02 Thread Hans Mulder

On 3/10/11 06:37:43, Steven D'Aprano wrote:

On Fri, 30 Sep 2011 21:09:54 +0100, Nobody wrote:


On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote:


I have a Python script which I would like to test without a tty
attached to the process. I could run it as a cron job, but is there an
easier way?

[...]

I suspect that the OP just wants e.g.:

script.py&>/dev/null<&-

which will redirect stdout and stderr to /dev/null and close stdin.



No, that's not what I wanted.

I ended up just running the script as a cron job. It was a one-off (well,
twice actually, since the first time demonstrated a bug in my code) test
of some code that tries to determine the size of the current terminal. I
wanted to ensure that it would do the right thing when run without a tty,
such as from a cron job.


In that case, the "at" command would have been the answer.
It is a bit like cron, but meant for one-off jobs.

You might have received more useful answers if you'd
mentioned you goals earlier.

-- HansM

--
http://mail.python.org/mailman/listinfo/python-list


Re: Python without a tty

2011-10-02 Thread Hegedüs , Ervin
hello,

On Mon, Oct 03, 2011 at 04:37:43AM +, Steven D'Aprano wrote:
> 
> I wanted to ensure that it would do the right thing when run without a tty, 
> such as from a cron job.

If you fork() your process, then it will also loose the tty...


import os
import sys


try: 
pid = os.fork() 
if pid > 0:
sys.exit(0) 
except OSError, e: 
sys.exit(1)

os.chdir("/") 
os.setsid() 
os.umask(0) 




a.

-- 
http://mail.python.org/mailman/listinfo/python-list


Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str

2011-10-02 Thread Wong Wah Meng-R32813
Hello guys,

I am migrating my application from python 1.5.2 to 2.7.1. I encountered an 
error when I run some commands (I put in debug statement however, not able to 
trace down to which line of code that cause it to generate a lot of messages in 
one second until my hard disk space is full. The error log I got in my log file 
is as below:-

Oct  3 14:12:41  ('Encountered exception while processing from', (0, 
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or 
derived from BaseException, not str',))

Does it mean in newer python I need to migrate all my Exception to non-string 
based exception type? That's should be a lot of changes. :p

Regards,
Wah Meng



-- 
http://mail.python.org/mailman/listinfo/python-list