Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Jack Trades wrote in
news:CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w...@mail.gmail.com
in gmane.comp.python.general: 

>> def test():
>>  src = (
>>   "def double(x):"
>>  "  return x * 2"
>> )
>>  globals  = {}
>>  exec( src, globals )
>>  return globals[ "double" ]
>>
>> print( test() )
>>
> 
> I looked into doing it that way but it still requires that the user
> use a specific name for the function they are defining.  The docs on
> exec say that an implementation may populate globals or locals with
> whatever they want so that also rules out doing a simple "for item in
> globals", as there may be more than just the one function in there
> (though I suppose I may be able to work around that).
> 
> 

Why not just get the name from the user, or use a regular expression
to extract the first (or last, maybe) definition from the source string.

Rob.

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Jack Trades wrote in news:CAG5udOiOAge3uHrGSDTZ412GAg+CC-
6u8igoyj0lnf3hnwu...@mail.gmail.com in gmane.comp.python.general:

>> >>> class CapturingDict(dict):
>> ... def __setitem__(self, key, val):
>> ... self.key, self.val = key, val
>> ... dict.__setitem__(self, key, val)
>> ...
>> >>> c = CapturingDict()
>> >>> exec("def myfunction(x): return 1", c)
>> >>> c.key
>> 'myfunction'
>> >>> c.val
>> 
>>
>> HTH,
>>
>> --
>> Arnaud
>>
> 
> That's brilliant and works flawlessly.  Thank you very much!

If an impementation (as you say up thread) can populate globals 
or locals with whatever they want, then how do you know that last 
item added was the function definition the user supplied ?

Rob.

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


Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`?

2011-08-30 Thread Michel Albert
Hi,

I use python oftentimes to write automation scripts on Linux servers.
And there's a big pattern in my scripts:

- I *always* use `logging` instead of `print` statements.
- I *always* create two stream handlers. One for `sys.stdout` with
level `INFO` and one for `sys.stderr` with level `WARN`

Well, the levels may variate occasionally, but that's only the rare
exception.

The reason I do this is simple: Most automation tasks are run via
cron. With this setup, I can redirect `stdout` to `/dev/null` and
still receive e-mails if things go wrong.

And having two handlers gives me more flexibility in my scripts. In
one case, I used a different color for error messages for example as
this script is run primarily from the shell and having errors stand
out has proven to be a good thing.

Unfortunately this setup makes `logging.basicConfig` pretty useless.
However, I believe that this is something that more people could
benefit from. I also believe, that it just "makes sense" to send
warnings (and above) to `stderr`, the rest to `stdout`.

So I was thinking: "Why does `logging.basicConfig` not behave that
way".

Naturally, I was thinking of writing a patch against the python
codebase and submit it as a suggestion. But before doing so, I would
like to hear your thoughts on this. Does it make sense to you too or
am I on the wrong track? Are there any downsides I am missing?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me understand this logging config

2011-08-30 Thread Peter Otten
Roy Smith wrote:

> I'm using django 1.3 and python 2.6.

Isn't dictConfig() new in 2.7? It looks like that is what you are using...

> My logging config is:
> 
> 
> LOGGING = {
> 'version': 1,
> 'disable_existing_loggers': False,
> 'formatters': {
> 'verbose': {
> 'format': '%(asctime)s: %(name)s %(levelname)s %
> (funcName)s %(message)s'
> }
> },
> 'handlers': {
> 'mail_admins': {
> 'level': 'ERROR',
> 'class': 'django.utils.log.AdminEmailHandler'
> },
> 'console': {
> 'level': 'DEBUG',
> 'class': 'logging.StreamHandler',
> 'formatter': 'verbose',
> },
> },
> 'loggers': {
> 'django.request': {'handlers': ['mail_admins'],
>'level': 'ERROR',
>'propagate': True,
>},
> 'djfront': {'handlers': ['console'],
> 'propagate': True,
> },
> 'djfront.view': {'level': 'INFO'},
> 'djfront.auth': {'level': 'INFO'},
> 'djfront.auth.user': {'level': 'INFO'},
> 'djfront.api': {'level': 'WARN'},
> }
> }
> 
> In my code, I do:
> 
> logger = logging.getLogger('djfront.auth.facebook')
> 
> Since I haven't configured a 'djfront.auth.facebook' logger, it should
> inherit the 'djfront.auth' config, which means the logging level
> should be set to INFO.  But, when I do:
> 
> logger.debug('redirecting to "%s"' % url)
> 
> it emits a message:
> 
> 2011-08-29 13:31:03,321: djfront.auth.facebook DEBUG oauth_init
> redirecting to [...]
> 
> I'm confused.  Why is the debug level message not getting filtered
> out?

I tried your setup with the django-specific handler replaced by another 
StreamHandler

$ cat tmp_logging.py
import logging
import logging.config

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(asctime)s: %(name)s %(levelname)s %(funcName)s 
%(message)s'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'logging.StreamHandler' 
#'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django.request': {'handlers': ['mail_admins'],
   'level': 'ERROR',
   'propagate': True,
   },
'djfront': {'handlers': ['console'],
'propagate': True,
},
'djfront.view': {'level': 'INFO'},
'djfront.auth': {'level': 'INFO'},
'djfront.auth.user': {'level': 'INFO'},
'djfront.api': {'level': 'WARN'},
}
}

logging.config.dictConfig(LOGGING)

logger = logging.getLogger('djfront.auth.facebook')
logger.info("info-test")
logger.debug("debug-test")

and got what

$ python2.7 tmp_logging.py
2011-08-30 11:18:33,160: djfront.auth.facebook INFO  info-test
$

which seems to be what you expected. So I'm confused, too...

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


Re: Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`?

2011-08-30 Thread Peter Otten
Michel Albert wrote:

> I use python oftentimes to write automation scripts on Linux servers.
> And there's a big pattern in my scripts:
> 
> - I *always* use `logging` instead of `print` statements.
> - I *always* create two stream handlers. One for `sys.stdout` with
> level `INFO` and one for `sys.stderr` with level `WARN`
> 
> Well, the levels may variate occasionally, but that's only the rare
> exception.

How would a call to basicConfig() look like that produces this setup?

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


Re: killing a script

2011-08-30 Thread Hans Mulder

On 30/08/11 06:13:41, Steven D'Aprano wrote:

On Tue, 30 Aug 2011 08:53 am Arnaud Delobelle wrote:

[...]

Yes, but if I am not mistaken, that will require me to put a line or
two after each os.system call. That's almost like whack-a-mole at the
code level rather than the Control-C level. OK, not a huge deal for
one script, but I was hoping for something simpler. I was hoping I
could put one line at the top of the script and be done with it.


Write a function!  That's what they're for after all :)



I'm not sure that this is actually as simple as that, especially using
os.system.

As I understand it, the scenario is this:

The main script looks something like this:

for x in whatever:
 os.system('something.py x')

Each time through the loop, a new Python process is started. Each process
runs in the foreground, capturing standard input, and so hitting Ctrl-C
kills *that* process, not the main script. Unless, by chance, the Ctrl-C
happens after the system call returns, but before the next one starts, it
is completely invisible to the parent process (the main script). Wrapping
os.system in a function does nothing to fix that.

Possibly using the subprocess module may help.


Using the subprocess module is likely to help, because unlike os.system,
subprocess does not set control-C to 'ignore' in the parent process


Otherwise, the only way around this I can think of is to ensure that
the 'something.py' script (or scripts!) each return an error code for "User
Cancelled":

for x in whatever:
 result = os.system('something.py x')
 if result == 3:  # User Cancelled
 break


On my system, os.system returns 2 if the subprocess was killed by a
control-C.  The portable way is to use the constant SIGINT from the
signal module.

Not that os.system does not return 2 if the child ended by doing
sys.exit(2); in that case, os.system in the parent returns 2<<8.


But if the 'something.py' scripts are arbitrary scripts, I don't think you
have any easy way around it.


If the arbitrary script does not trap SIGINT, then os.system
will return the number of the signal that kill the script, i.e.
signal.SIGINT.

If the script traps SIGINT and does some cleanup and then
exits, the best you can hope for, is that in the error case,
the script exits with a special value.  And you have to
remember the <<8 issue.


Perhaps use threads, and have the main script
ask the thread to kill the child process?


How would that help?

The problem is that the parent process ignores control-C while
os.system is running (by design).  If the parent uses threads,
it still won't receive the signal, because signal state is
global.


Regardless, this is a hard problem, and it isn't possible to just have some
magic switch at the top of your script to make it work. You actually have
to do the work yourself.


You could monkey-patch the os module and replace os.system by
(untested):

def sub_system(command):
pr = subprocess.Popen(command, shell=True)
status = os.waitpid(pr.pid, 0)[1]
return status

That should have the same effect as os.system, except it does
not ignore control-C.


(But of course you can do the work inside a function, and re-use it
elsewhere.)


Even if you don't re-use it, you should still do it in a
function, if only for readability.

Hope this helps,

-- HansM



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


Re: Help me understand this logging config

2011-08-30 Thread anand jeyahar
Hi,
   I took a look at the logging source code. getLogger checks for existing
loggers with the given name and if it doesn't creates one.



def getLogger(self, name):
"""
Get a logger with the specified name (channel name), creating it
if it doesn't yet exist. This name is a dot-separated hierarchical
name, such as "a", "a.b", "a.b.c" or similar.

If a PlaceHolder existed for the specified name [i.e. the logger
didn't exist but a child of it did], replace it with the created
logger and fix up the parent/child references which pointed to the
placeholder to now point to the logger.
"""
rv = None
_acquireLock()
try:
if name in self.loggerDict:
rv = self.loggerDict[name]
if isinstance(rv, PlaceHolder):
ph = rv
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupChildren(ph, rv)
self._fixupParents(rv)
else:
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupParents(rv)
finally:
_releaseLock()
return rv

==
Anand Jeyahar
https://sites.google.com/site/
anandjeyahar
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
  ~Bruce Lee

Love is a trade with lousy accounting policies.
 ~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help parsing a text file

2011-08-30 Thread Waldek M.
On Mon, 29 Aug 2011 23:05:23 +0200, Thomas Jollans wrote:
> A name that is often thrown around on this list for this kind of
> question is pyparsing. Now, I don't know anything about it myself, but
> it may be worth looking into.

Definitely. I did use it and even though it's not perfect - it's very
useful indeed. Due to it's nature it is not a demon of speed when parsing
complex and big structures, so you might want to keep it in mind.
But I whole-heartedly recommend it.

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


Re: Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`?

2011-08-30 Thread Michel Albert
On Aug 30, 11:45 am, Peter Otten <__pete...@web.de> wrote:
> Michel Albert wrote:
> > I use python oftentimes to write automation scripts on Linux servers.
> > And there's a big pattern in my scripts:
>
> > - I *always* use `logging` instead of `print` statements.
> > - I *always* create two stream handlers. One for `sys.stdout` with
> > level `INFO` and one for `sys.stderr` with level `WARN`
>
> > Well, the levels may variate occasionally, but that's only the rare
> > exception.
>
> How would a call to basicConfig() look like that produces this setup?

I personally see this happen by default (i.e. no additional
parameters). And in case the `stream` parameter is set, /then/ you
would  send all to that stream only.

In my point of view, the call to `basicConfig` is either something
used in only the most mundane usages of the logging package, or it's
mainly used by people that have not yet grokked the logging package
(correct me if I'm wrong). In both cases, I find it useful to redirect
warnings and errors to `stderr` by default.

However, this would also mean that existing code calling this method
would result in different behavior. But only /slightly/ different.
Meaning, you still see the output on the console as expected. But it
gives you the possibility to use standard shell redirection in a way
that "makes sense".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Jack Trades
On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft  wrote:


> > That's brilliant and works flawlessly.  Thank you very much!
>
> If an impementation (as you say up thread) can populate globals
> or locals with whatever they want, then how do you know that last
> item added was the function definition the user supplied ?
>
> Rob.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


I spoke a bit too soon with the "works flawlessly" post.  In addition to
your issue, there is also the problem that supplying an empty environment
does not allow the user to call necessary functions (like scheme_eval).


Why not just get the name from the user
>

That's probably what I'll end up doing, something similar to:

special_forms = {}

def exec_func_def(symbol, def_string, name=None):
  exec(def_string)
  if name is None:
special_forms[symbol] = f
  else:
special_forms[symbol] = eval(name)

It just feels kind of hackish to me, when what I really want to do here is
eval an anonymous function.

-- 
Nick Zarczynski 
Pointless Programming Blog 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me understand this logging config

2011-08-30 Thread Roy Smith
In article ,
 Peter Otten <__pete...@web.de> wrote:

> Roy Smith wrote:
> 
> > I'm using django 1.3 and python 2.6.
> 
> Isn't dictConfig() new in 2.7? It looks like that is what you are using...

Oh, my, it turns out that django includes:

# This is a copy of the Python logging.config.dictconfig module,

# reproduced with permission. It is provided here for backwards 

# compatibility for Python versions prior to 2.7. 

Comparing the django copy to lib/logging/config.py from Python 2.7.2, 
they're not identical.  It's likely they grabbed something earlier in 
the 2.7 series.  I'll check 2.7.0 and 2.7.1 to see.

> I tried your setup with the django-specific handler replaced by another 
> StreamHandler
> [...]
> and got what
> 
> $ python2.7 tmp_logging.py
> 2011-08-30 11:18:33,160: djfront.auth.facebook INFO  info-test
> $
> 
> which seems to be what you expected. So I'm confused, too...

I'll need to dig deeper.  Not that I realize this may not be a Python 
issue per-se, I'll do some more experimentation and ask on the django 
mailing list.  Thanks for your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unpickle error -- "object has no attribute ...."

2011-08-30 Thread Peter Otten
luvspython wrote:

> THANK YOU!  Special-casing "__dict__" did the trick.  Not sure I'd
> have ever figured that out, which leads to a different question:
> 
> I can figure out most things, though perhaps very slowly and
> painfully, if I can trace through code.  I use WingIDE (love it), but
> the execution
> of the C code is of course hidden, which helped stymie on this
> problem.  Is there another tool y'all might use and you can suggest
> that deals with that problem and would have helped me with this case?
> Or is one's ability to figure out this sort of problem largely
> dependent on really understanding the system's internals?

I'm with Chris here, I make do with some understanding of Python and a 
generous amount of print statements. My other secret weapon is that I try to 
keep the complexity of my code low ;)

As Python is yet another C program you can of course step through its code 
(debug build) with an appropriate debugger, but I've never done that. My 
guess is that you wouldn't have seen the forest for the trees.


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


SQLObject 1.1.3

2011-08-30 Thread Oleg Broytman
Hello!

I'm pleased to announce version 1.1.3, a bugfix release of branch
1.1 of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://pypi.python.org/pypi/SQLObject/1.1.3

News and changes:
http://sqlobject.org/News.html


What's New
==

Features & Interface


* Fixed a bug with Postgres - add quotes in "SET client_encoding" query.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmanhttp://phdru.name/p...@phdru.name
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


can't create instance of pythoncom server

2011-08-30 Thread Johanna
Hi all,

I am trying to consume a Pythoncom server from 3ds max. I need this to be
able to call some mysql queries in python script from maxscript. I tried to
follow the steps in this article.

I created a small pythoncom server

import sys, os
def getWorkingDirectory() :
return os.path.dirname(sys.argv[0])
sys.path.append('tubeBDD')
from Database import Database
import selectBDD as select


db = Database()

# A simple Python COM server.
class PythonComUtilities:
_public_methods_ = ['getProjects']
_reg_progid_ = 'PythonCom.Utilities'
# Class ID must be new/unique for every server you create
_reg_clsid_ = '{BAC62D37-EEDF-46B3-8DED-11E842225B0E}'


def getProjects(self, string):
# self.db = Database()
projects = select.getProjects(db)
proj = ""
for p in projects:
if proj == "":
proj = p[0]
else:
proj = proj + "," + p[0]
return proj


if (__name__ == '__main__'):
print 'Registering COM server...'
import win32com.server.register as comReg
comReg.UseCommandLine(PythonComUtilities)

Then I try to call it in a maxscript (in a 3D soft):

comObj = createOLEObject "PythonCom.Utilities"

It gives me this error :

-- Runtime error: createOLEObject: can't create instance PythonCom.Utilities

Any idea what I'm doing wrong ?
Or any idea of how I could test it other than in the 3D soft ?

Cheers,
Johanna
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Ethan Furman

Jack Trades wrote:

On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft wrote:

If an impementation (as you say up thread) can populate globals
or locals with whatever they want, then how do you know that last
item added was the function definition the user supplied ?


Because the implementation will add things before the exec is processed. 
 Then when the exec actually runs, any assignments, definitions, etc, 
from the user supplied string will be added.



I spoke a bit too soon with the "works flawlessly" post.  In addition to 
your issue, there is also the problem that supplying an empty 
environment does not allow the user to call necessary functions (like 
scheme_eval).


So, just like an implementation, add the functions to the CapturingDict 
before the exec.


One thing to keep in mind:  the CapturingDict only remembers the *last* 
thing created/assigned... so if the user code has more than one 
def/class/name assignment, you won't have ready access to the first 
items, only that last one.


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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Ethan Furman wrote in news:4e5d29c8.8010...@stoneleaf.us in 
gmane.comp.python.general:

> Jack Trades wrote:
>> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft wrote:
>>> If an impementation (as you say up thread) can populate globals
>>> or locals with whatever they want, then how do you know that last
>>> item added was the function definition the user supplied ?
> 
> Because the implementation will add things before the exec is processed. 

How do you know this ?, it isn't what the docs say.

http://docs.python.org/reference/simple_stmts.html#the-exec-statement

Rob.

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


Installing WebDAV server

2011-08-30 Thread Fokke Nauta
Hi all,

I am completely new to Python, but I'm confronted with a problem I can't 
solve.
This is my question:

I'm running a PC with XP Pro32, which acts as a file server/print server/FTP 
server and web server. The web server is facilitated by the Aprelium Abyss 
X2 server, and has Perl and PHP support on http and https. It all works 
fine.
To do some research with some calender systems and to share the Outlook 
calendar I need a WebDAV server. After googling I found the Python WebDAV 
server.
I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML. Now 
I have a working Python app and 2 directories called PyWebDAV-0.9.4.1 and 
PyXML-0.8.4. In the PyWebDAV README it says:

Installation and setup of server can be as easy as follows:

$ easy_install PyWebDAV
$ davserver -D /tmp -n -J

But of course it doesn't work like that. When I start up Python GUI I see 
the ">>>" prompt instead of the "$" prompt. But where do I place the two 
directories? And there is no easy_install script in the PyXML-0.8.4 
directory, only a setup.py and ez_setup.py script. I guess the latter is the 
one to use. But how?

How do I proceed next?

Any help will be appreciated.
Thanks in advance.

With regards,
Fokke Nauta



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


Re: Installing WebDAV server

2011-08-30 Thread Thomas 'PointedEars' Lahn
Fokke Nauta wrote:

> I'm running a PC with XP Pro32, […]
> To do some research with some calender systems and to share the Outlook
> calendar I need a WebDAV server. After googling I found the Python WebDAV
> server.
> I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML.
> Now I have a working Python app and 2 directories called PyWebDAV-0.9.4.1
> and PyXML-0.8.4. In the PyWebDAV README it says:
> 
> Installation and setup of server can be as easy as follows:
> 
> $ easy_install PyWebDAV
> $ davserver -D /tmp -n -J
> 
> But of course it doesn't work like that. When I start up Python GUI

That is really not a *G*raphical User Interface, but the (text-based) Python 
shell.

> I see the ">>>" prompt instead of the "$" prompt.

  "Doctor, my arm hurts when I move it." – "Don't move it, then."

The Python shell executes Python code.  The above obviously is not Python 
code, but *system* shell commands.  So let the *system* command shell 
execute them (as indicated by the `$' prompt, which is customary for a
sh-based UNIX/Linux shell prompt).  

Since you use Windows XP, type `cmd' to get the command shell (if you knew 
MS-DOS, which I doubt, you are at home now).  However, you appear to have 
found the *UNIX/Linux* README (and the corresponding version?) of that 
server: the second command is usually how you would run a program as daemon 
on Unices (run through an init script), while on Windows NT (like XP) you 
would have a setup program install a service for you (maybe to execute that 
command when the service is started).  Look for the Windows version.

> But where do I place the two directories?

You do not; let easy_install place them in the correct packages directory 
(hence *easy* *install*).  That is very likely what the setup.py and 
ez_setup.py scripts are for (spell "ez" in English).

> And there is no easy_install script in the PyXML-0.8.4
> directory, only a setup.py and ez_setup.py script. I guess the latter is
> the one to use. But how?

RTFM.
 
> How do I proceed next?

Look for the Windows version.  If there is none, get easy_install and use it 
as described.

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Usage of PyDateTime_FromTimestamp

2011-08-30 Thread Andreas
Hi,

I'm working on a c-extension of python and want to create an instance of
python datetime object with a unix timestamp in c.

On the documentation site ( http://docs.python.org/c-api/datetime.html )
I found the function PyDateTime_FromTimestamp() which returns a new
reference based on an input parameter.

The description is as follows: Create and return a new datetime.datetime
object given an argument tuple suitable for passing to
datetime.datetime.fromtimestamp().

I tried out to call the function with a PyFloat_Object but the function
always returns NULL (even if I simply put in 0).

Does somebody have an example how I have to call the function or can
give a hint what kind of parameter tuple is required to get it work?

Thanks!

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Ethan Furman

Rob Williscroft wrote:
Ethan Furman wrote in news:4e5d29c8.8010...@stoneleaf.us in 
gmane.comp.python.general:



Jack Trades wrote:

On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft wrote:

If an impementation (as you say up thread) can populate globals
or locals with whatever they want, then how do you know that last
item added was the function definition the user supplied ?
Because the implementation will add things before the exec is processed. 


How do you know this ?, it isn't what the docs say.

http://docs.python.org/reference/simple_stmts.html#the-exec-statement


The docs don't say when, true -- so I don't know for sure that all 
additions happen before the exec since I haven't delved into the source 
code...


Okay, just perused builtin_exec in bltinmodule.c, and I can say that 
cPython (somewhere in 3.2-3.3 land) only adds __builtins__ if not 
already there, and that it does it first.


Which makes sense -- after all, what's the point of adding stuff to 
globals() *after* the code has been run?


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


Python Tools for Visual Studio - anyone using it?

2011-08-30 Thread Philip Semanchuk
Hi all,
I was reminded today (via Slashdot) of Python Tools for Visual Studio which was 
discussed on this list back in March 
(http://mail.python.org/pipermail/python-list/2011-March/1267662.html) and has 
reached version 1.0. Is anyone here using it? Care to share pros & cons?

Here's the URL for those who haven't heard of it before:
http://pytools.codeplex.com/

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Arnaud Delobelle
On 30 August 2011 13:31, Jack Trades  wrote:
>
>
> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft  wrote:
>
>>
>> > That's brilliant and works flawlessly.  Thank you very much!
>>
>> If an impementation (as you say up thread) can populate globals
>> or locals with whatever they want, then how do you know that last
>> item added was the function definition the user supplied ?

That's not an issue. The last statement that is executed will be the
"def" statement.

>> Rob.
>
> I spoke a bit too soon with the "works flawlessly" post.  In addition to
> your issue, there is also the problem that supplying an empty environment
> does not allow the user to call necessary functions (like scheme_eval).

You could simply prepend the function definition string with whatever
imports are needed.

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


Re: Installing WebDAV server

2011-08-30 Thread Fokke Nauta
"Thomas 'PointedEars' Lahn"  wrote in message 
news:6545843.yvfaxzv...@pointedears.de...
> Fokke Nauta wrote:
>
>> I'm running a PC with XP Pro32, [.]
>> To do some research with some calender systems and to share the Outlook
>> calendar I need a WebDAV server. After googling I found the Python WebDAV
>> server.
>> I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML.
>> Now I have a working Python app and 2 directories called PyWebDAV-0.9.4.1
>> and PyXML-0.8.4. In the PyWebDAV README it says:
>>
>> Installation and setup of server can be as easy as follows:
>>
>> $ easy_install PyWebDAV
>> $ davserver -D /tmp -n -J
>>
>> But of course it doesn't work like that. When I start up Python GUI
>
> That is really not a *G*raphical User Interface, but the (text-based) 
> Python
> shell.

Yes, I noticed. But the application has the name of Python GUI.

>> I see the ">>>" prompt instead of the "$" prompt.
>
>  "Doctor, my arm hurts when I move it." - "Don't move it, then."

I don't see the point here ...

> The Python shell executes Python code.  The above obviously is not Python
> code, but *system* shell commands.  So let the *system* command shell
> execute them (as indicated by the `$' prompt, which is customary for a
> sh-based UNIX/Linux shell prompt).

I know. I worked with SCO Unix and various sorts of Linux.
But never with Python, so I hadn't got a clue about the prompt.

> Since you use Windows XP, type `cmd' to get the command shell (if you knew
> MS-DOS, which I doubt, you are at home now).

I know MSDOS. I even worked with CP/M

> However, you appear to have
> found the *UNIX/Linux* README (and the corresponding version?) of that
> server: the second command is usually how you would run a program as 
> daemon
> on Unices (run through an init script), while on Windows NT (like XP) you
> would have a setup program install a service for you (maybe to execute 
> that
> command when the service is started).  Look for the Windows version.

There is no other Windows version except the packages I mentioned,  PyWebDAV 
and PyXML.
The only Windows thing I got was the Python interpreter itself.

>> But where do I place the two directories?
>
> You do not; let easy_install place them in the correct packages directory
> (hence *easy* *install*).  That is very likely what the setup.py and
> ez_setup.py scripts are for (spell "ez" in English).
>
>> And there is no easy_install script in the PyXML-0.8.4
>> directory, only a setup.py and ez_setup.py script. I guess the latter is
>> the one to use. But how?
>
> RTFM.

Which fucking manual?

>> How do I proceed next?
>
> Look for the Windows version.  If there is none, get easy_install and use 
> it
> as described.
>

Thanks for your quick reply.
This means "Show over"?

Fokke 


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


RE: Get reference to parent class from subclass?

2011-08-30 Thread Prasad, Ramit
-Original Message-
From: python-list-bounces+ramit.prasad=jpmorgan@python.org 
[mailto:python-list-bounces+ramit.prasad=jpmorgan@python.org] On Behalf Of 
John O'Hagan
Sent: Saturday, August 27, 2011 11:00 PM
To: python-list@python.org
Subject: Get reference to parent class from subclass?

class P():
pass

class C(P):
pass

Can I get P from C? 

IOW, can I get a reference to the object P from the object C? This should be 
obvious one way or the other, but I haven't been able to find the answer.

Regards,

John
-- 


You should be able to access what you need via the super() built-in. I am not 
entirely sure what you are trying to do...but I think usage of super is 
probably better than trying to access the base classes manually.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Access LDAP with Django

2011-08-30 Thread John Riselvato
Would Django be a good framework to use if i wanted to take directories of
LDAP and make a list of users on a website? I have seen it done in php, but
what about trying to manage this with django?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Arnaud Delobelle wrote in 
news:CAJ6cK1YVi3NQgdZOUdhAESf133pUkdazM1PkSP=p6xfayvo...@mail.gmail.com in 
gmane.comp.python.general:

> On 30 August 2011 13:31, Jack Trades  wrote:
>>
>>
>> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft  wrote:
>>
>>>
>>> > That's brilliant and works flawlessly. ¶ÿThank you very much!
>>>
>>> If an impementation (as you say up thread) can populate globals
>>> or locals with whatever they want, then how do you know that last
>>> item added was the function definition the user supplied ?

> That's not an issue. The last statement that is executed will be the
> "def" statement.

You don't know that, an implementation may for example set __bultins__ 
to None, prior to returning, its not an unreasonable thing to do and
the docs don't say they can't.

Rob.

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


Re: Usage of PyDateTime_FromTimestamp

2011-08-30 Thread MRAB

On 30/08/2011 21:42, Andreas wrote:

Hi,

I'm working on a c-extension of python and want to create an instance of
python datetime object with a unix timestamp in c.

On the documentation site ( http://docs.python.org/c-api/datetime.html )
I found the function PyDateTime_FromTimestamp() which returns a new
reference based on an input parameter.

The description is as follows: Create and return a new datetime.datetime
object given an argument tuple suitable for passing to
datetime.datetime.fromtimestamp().

I tried out to call the function with a PyFloat_Object but the function
always returns NULL (even if I simply put in 0).

Does somebody have an example how I have to call the function or can
give a hint what kind of parameter tuple is required to get it work?


The key phrase is "argument tuple". The arguments passed to a Python
call are always a tuple, not PyFloat_Object.

You can build a tuple from the PyFloat_Object using:

Py_BuildValue("(O)", float_object)

The "(O)" says to build a tuple ("(...)") containing a single object
("O").
--
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Ethan Furman

Rob Williscroft wrote:

Arnaud Delobelle wrote:

That's not an issue. The last statement that is executed will be the
"def" statement.


You don't know that, an implementation may for example set __bultins__ 
to None, prior to returning, its not an unreasonable thing to do and

the docs don't say they can't.


Yet another excellent reason to have unit tests!

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Ethan Furman

Rob Williscroft wrote:

Arnaud Delobelle wrote:


That's not an issue. The last statement that is executed will be the
"def" statement.


You don't know that, an implementation may for example set __bultins__ 
to None, prior to returning, its not an unreasonable thing to do and

the docs don't say they can't.


Actually, I think it is unreasonable -- by modifying the globals or 
locals objects *after* the code has been exec'd, information is being 
removed about the environment the code ran in, making introspection (if 
nothing else) more difficult.


Good reasons are required to make life difficult (at least with Python).

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Jack Trades
On Tue, Aug 30, 2011 at 1:19 PM, Ethan Furman  wrote:

>
> I spoke a bit too soon with the "works flawlessly" post.  In addition to
>> your issue, there is also the problem that supplying an empty environment
>> does not allow the user to call necessary functions (like scheme_eval).
>>
>
>
> So, just like an implementation, add the functions to the CapturingDict
> before the exec.
>
>
I will probably do that a bit down the road, that also allows exporting only
the things that are absolutely necessary, which is a huge plus.  Right now
I'm trying to keep the code as simple as possible as this Scheme interpreter
is being written as a tutorial in a similar fashion to "An Incremental
Approach to Compiler Construction".  I'll add a note about this method of
implementation and link to this discussion.

In the off chance anyone is interested, the series is
hereand the github
is
here .  It's still very much
in draft form and will probably undergo a number of rewrites, but criticism
is always welcome.

-- 
Nick Zarczynski
Pointless Programming Blog 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/Eclipse

2011-08-30 Thread Fabio Zadrozny
On Fri, Aug 26, 2011 at 11:18 AM, Dave Boland  wrote:
> I'm looking for a good IDE -- easy to setup, easy to use -- for Python.  Any
> suggestions?
>
> I use Eclipse for other projects and have no problem with using it for
> Python, except that I can't get PyDev to install.  It takes forever, then
> produces an error that makes no sense.
>
> An error occurred while installing the items
>  session context was:(profile=PlatformProfile,
> phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Install,
> operand=null --> [R]org.eclipse.cvs 1.0.400.v201002111343,
> action=org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.InstallBundleAction).
>  Cannot connect to keystore.
>  This trust engine is read only.
>  The artifact file for osgi.bundle,org.eclipse.cvs,1.0.400.v201002111343 was
> not found.
>
>
> Any suggestions on getting this to work?

In the install dialog, uncheck the 'contact all update sites during
install to find required software'.

Another option would be getting Aptana Studio 3, which has PyDev
preinstalled (see: http://pydev.org/download.html )

Cheers,

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


Re: Installing WebDAV server

2011-08-30 Thread Thomas 'PointedEars' Lahn
Fokke Nauta wrote:

> "Thomas 'PointedEars' Lahn"  wrote in message
> news:6545843.yvfaxzv...@pointedears.de...

It's attribution _line_, not attribution novel.  Your quotes are hardly 
legible, too → 

>> Fokke Nauta wrote:
>>> I'm running a PC with XP Pro32, [.]
>>> […] In the PyWebDAV README it says:
>>>
>>> Installation and setup of server can be as easy as follows:
>>>
>>> $ easy_install PyWebDAV
>>> $ davserver -D /tmp -n -J
>>>
>>> But of course it doesn't work like that. When I start up Python GUI
>> That is really not a *G*raphical User Interface, but the (text-based)
>> Python shell.
> 
> Yes, I noticed. But the application has the name of Python GUI.

ACK.  Admittedly I cannot remember having used Python on Windows (XP) except 
via Cygwin.
 
>>> I see the ">>>" prompt instead of the "$" prompt.
>>  "Doctor, my arm hurts when I move it." - "Don't move it, then."
> 
> I don't see the point here ...

Do not run `python' or the "Python GUI", then.

>> The Python shell executes Python code.  The above obviously is not Python
>> code, but *system* shell commands.  So let the *system* command shell
>> execute them (as indicated by the `$' prompt, which is customary for a
>> sh-based UNIX/Linux shell prompt).
> 
> I know. I worked with SCO Unix and various sorts of Linux.
> But never with Python, so I hadn't got a clue about the prompt.

Come on, with that experience you see a `$' and those commands and don't 
realize it is (ba)sh?
 
>> Since you use Windows XP, type `cmd' to get the command shell (if you
>> knew MS-DOS, which I doubt, you are at home now).
> 
> I know MSDOS. I even worked with CP/M

Good for you.

>> However, you appear to have found the *UNIX/Linux* README (and the
>> corresponding version?) of that server: the second command is usually how
>> you would run a program as daemon on Unices (run through an init script),
>> while on Windows NT (like XP) you would have a setup program install a
>> service for you (maybe to execute that command when the service is
>> started).  Look for the Windows version.
> 
> There is no other Windows version except the packages I mentioned, 
> PyWebDAV and PyXML. The only Windows thing I got was the Python
> interpreter itself.

Has it not occurred to you to STFW for "easy_install" first?

>>> And there is no easy_install script in the PyXML-0.8.4
>>> directory, only a setup.py and ez_setup.py script. I guess the latter is
>>> the one to use. But how?
>> RTFM.
> 
> Which fucking manual?

That of the server, on Windows-related information.  Or that of 
easy_install.  Or Python.  Whichever comes first.

>>> How do I proceed next?
>> Look for the Windows version.  If there is none, get easy_install and use
>> it as described.
> 
> Thanks for your quick reply.
> This means "Show over"?

No, it means "Do your homework".

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Handling 2.7 and 3.0 Versions of Dict

2011-08-30 Thread Travis Parks
I am writing a simple algorithms library that I want to work for both
Python 2.7 and 3.x. I am writing some functions like distinct, which
work with dictionaries under the hood. The problem I ran into is that
I am calling itervalues or values depending on which version of the
language I am working in. Here is the code I wrote to overcome it:

import sys
def getDictValuesFoo():
if sys.version_info < (3,):
return dict.itervalues
else:
return dict.values

getValues = getDictValuesFoo()

def distinct(iterable, keySelector = (lambda x: x)):
lookup = {}
for item in iterable:
key = keySelector(item)
if key not in lookup:
lookup[key] = item
return getValues(lookup)

I was surprised to learn that getValues CANNOT be called as if it were
a member of dict. I figured it was more efficient to determine what
getValues was once rather than every time it was needed.

First, how can I make the method getValues "private" _and_ so it only
gets evaluated once? Secondly, will the body of the distinct method be
evaluated immediately? How can I delay building the dict until the
first value is requested?

I noticed that hashing is a lot different in Python than it is in .NET
languages. .NET supports custom "equality comparers" that can override
a type's Equals and GetHashCode functions. This is nice when you can't
change the class you are hashing. That is why I am using a key
selector in my code, here. Is there a better way of overriding the
default hashing of a type without actually modifying its definition? I
figured a requesting a key was the easiest way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Handling 2.7 and 3.0 Versions of Dict

2011-08-30 Thread Terry Reedy

On 8/30/2011 9:43 PM, Travis Parks wrote:

I am writing a simple algorithms library that I want to work for both
Python 2.7 and 3.x. I am writing some functions like distinct, which
work with dictionaries under the hood. The problem I ran into is that
I am calling itervalues or values depending on which version of the
language I am working in. Here is the code I wrote to overcome it:

import sys
def getDictValuesFoo():
 if sys.version_info<  (3,):
 return dict.itervalues
 else:
 return dict.values


One alternative is to use itervalues and have 2to3 translate for you.
--
Terry Jan Reedy

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


Re: Usage of PyDateTime_FromTimestamp

2011-08-30 Thread Andreas
Am 30.08.2011 23:49, schrieb MRAB:

> The key phrase is "argument tuple". The arguments passed to a Python
> call are always a tuple, not PyFloat_Object.
> 
> You can build a tuple from the PyFloat_Object using:
> 
> Py_BuildValue("(O)", float_object)
> 
> The "(O)" says to build a tuple ("(...)") containing a single object
> ("O").

Thank you very much! That solved my problem.
Here the full working example:

static double doubleValue = 1314761451;
PyObject *floatObj = NULL;
PyObject *timeTuple = NULL;
PyObject *dateTime = NULL;

floatObj = PyFloat_FromDouble(doubleValue);
timeTuple = Py_BuildValue("(O)", floatObj);
dateTime = PyDateTime_FromTimestamp(timeTuple);




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


Re: Python IDE/Eclipse

2011-08-30 Thread Adam Jorgensen
I recommend PyCharm. Best Python IDE ever :-)

If you can't afford to pay for it in the long run, then PyDev is the next
best bet. I would recommend downloading the most
minimal Eclipse you can get (Usually the Eclipse RCP Runtime) and install
the necessary plugins as you go. This prevents
you from falling into the overloaded eclipse problem as quickly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help parsing a text file

2011-08-30 Thread Tim Roberts
William Gill  wrote:
>
>My initial passes into Python have been very unfocused (a scatter gun of 
>too many possible directions, yielding very messy results), so I'm 
>asking for some suggestions, or algorithms (possibly even examples)that 
>may help me focus.
>
>I'm not asking anyone to write my code, just to nudge me toward a more 
>disciplined approach to a common task, and I promise to put in the 
>effort to understand the underlying fundamentals.

Python includes "sgmllib", which was designed to parse SGML-based files,
including both neat XML and slimy HTML, and "htmllib", which derives from
it.  I have used "htmllib" to parse HTML files where the tags were not
properly closed.  Perhaps you could start from "htmllib" and modify it to
handle the quirks in your particular format.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from exec or a better solution

2011-08-30 Thread Arnaud Delobelle
On 30 August 2011 22:48, Rob Williscroft  wrote:
> Arnaud Delobelle wrote in
> news:CAJ6cK1YVi3NQgdZOUdhAESf133pUkdazM1PkSP=p6xfayvo...@mail.gmail.com in
> gmane.comp.python.general:
>
>> On 30 August 2011 13:31, Jack Trades  wrote:
>>>
>>>
>>> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft  wrote:
>>>

 > That's brilliant and works flawlessly. ś˙Thank you very much!

 If an impementation (as you say up thread) can populate globals
 or locals with whatever they want, then how do you know that last
 item added was the function definition the user supplied ?
>
>> That's not an issue. The last statement that is executed will be the
>> "def" statement.
>
> You don't know that, an implementation may for example set __bultins__
> to None, prior to returning, its not an unreasonable thing to do and
> the docs don't say they can't.

I haven't studied the docs but I'm certain that such an implementation
would break a lot of code.

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