Re: [BangPypers] Help On Paramiko

2012-06-19 Thread Guru
Refer this site you may get some useful information
http://segfault.in/2010/03/paramiko-ssh-and-sftp-with-python/


On Tue, Jun 19, 2012 at 12:00 PM, Noufal Ibrahim wrote:

>
> Fabric is a library built on paramiko that gives you abstractions so
> that you don't have to worry about things at such a fine grained
> level. Perhaps you should try using that.
>
>  writes:
>
> > Howdy All,
> >
> > I am trying to use paramiko to automate logging in to remote unix
> machines and executing some commands there.
> > When I normally do ssh from my linux machine (with Python 2.6) to this
> machine a different '>' prompt comes. It's a device specific custom prompt.
> > After I run 'enable' command here, a new prompt opens up. '#' which is
> also custom prompt.
> > Then I need to run 'configure terminal' there. And then some more device
> specific commands.
> >
> > i.e.
> > {{{
> > Linux # Ssh ad...@xx.xx.xx.xx
> >
> > Ø  Enable
> > # configure terminal
> > # 
> > }}}
> >
> > Can this be done using paramiko?
> > I tried with:
> >
> > {{{
> > import paramiko
> >
> > client = paramiko.SSHClient()
> > client.load_system_host_keys()
> > client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
> > client.connect('xx.xx.xx.xx', username='admin', password='')
> > stdin, stdout, stderr = client.exec_command('enable')
> > #stdin.write('configure t')
> > print(stdout.readlines())
> >
> > }}}
> > (There is no passwd for username admin.)
> >
> >
> > o/p
> > ['UNIX shell commands cannot be executed using this account.\n']
> >
> > Any suggestions?
> >
> > Thanks
> > Nikunj
> > ___
> > BangPypers mailing list
> > bangpyp...@python.org
> > http://mail.python.org/mailman/listinfo/bangpypers
> >
>
> --
> Cordially,
> Noufal
> http://nibrahim.net.in
> ___
> BangPypers mailing list
> bangpyp...@python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>



-- 
-REGARDS

Guruprasad K S
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pymongo Error

2012-06-19 Thread Alan Gauld

On 19/06/12 06:22, Ranjith Kumar wrote:


I tried Django with Mongodb while running manage.py syncdb I endup with
this error


You might be better off trying a mongo forum./mailing list since this 
list is for Python beginners and focuses on the Python language and std 
library. Django is not in the standard library but is sufficiently 
common that you may get a response there. But Mongo is a wee bit 
specialised so it will be pure luck if you find a Mongo user who can 
answer...



django.db.utils.DatabaseError: Ordering can't span tables on
non-relational backends (content_type__app_label)


Given we can't actually see the command you are trying to execute
its virtually impossible to know what Mongo/Django/Python is complaining 
about. We would need to know a lot more about your data structure and 
your query. What is it you are trying to order for example? Does it span 
tables?


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



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


Re: Conditional decoration

2012-06-19 Thread Gelonida N

On 06/19/2012 02:23 AM, Rob Williscroft wrote:

Roy Smith wrote in news:jro9cj$b44$1...@panix2.panix.com in
gmane.comp.python.general:


Is there any way to conditionally apply a decorator to a function?
For example, in django, I want to be able to control, via a run-time
config flag, if a view gets decorated with @login_required().

@login_required()
def my_view(request):
 pass


You need to create a decorator that calls either the original
function or the decorated funtion, depending on your condition,
Something like (untested):

def conditional_login_required( f ):
   _login_required = login_required()(f)

   def decorated( request ):
 if condition == "use-login":
   return _login_required( request )
 else:
   return f( request )

   return decorated

@conditional_login_required
def my_view(request):
   pass

Replace (condition == "use-login") with whatever your "run-time
control flag" is.



Your suggestion will unconditionally decorate a function and depending 
on the condition call the original function or not.


However if you want to evaluate the condition only once at decoration 
time, then you had probably to do something like (not tested)

> def conditional_login_required( f ):
>_login_required = login_required()(f)
>
>def decorated( request ):
>return _login_required( request )
>if condition:
> return decorated
>else:
>return f




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


Re: "constant sharing" works differently in REPL than in script ?

2012-06-19 Thread Chris Angelico
On Tue, Jun 19, 2012 at 12:52 PM,   wrote:
> ...Python pre creates some integer constants to avoid a proliferation of 
> objects with the same value.
>
> I was interested in this and so I decided to try it out.
> So that matched what I'd heard and then I did this to test the limits of it :
>
> And that was reasonable too as the podcast mentioned it was only done for a 
> small set of integers around zero.

The exact set varies according to Python version and, as others have
mentioned, shouldn't be relied upon.

import sys
print(sys.version)
wascached=False
for i in range(-100,300):
j=i+1
j-=1
if (i is j)!=wascached:
wascached=i is j
if wascached:
firstcache=i
else:
print("%d to %d are cached"%(firstcache,i-1))
break

2.4.5 (#1, Jul 22 2011, 02:01:04)
[GCC 4.1.1]
-5 to 99 are cached

2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)]
-5 to 256 are cached

3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]
-5 to 256 are cached

It's definitely something that's fun to play with, though not
something to take ANY notice of in real code :)

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


Re: Conditional decoration

2012-06-19 Thread Jean-Michel Pichavant

Roy Smith wrote:

Is there any way to conditionally apply a decorator to a function?
For example, in django, I want to be able to control, via a run-time
config flag, if a view gets decorated with @login_required().

@login_required()
def my_view(request):
pass
  

Hi,


def my_view(request):
   pass

if flag: my_view = login_required(my_view)

Regards,

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


Converting html character codes to utf-8 text

2012-06-19 Thread Johann Spies
I am trying the following:

Change data like this:

Bien Donné : agri tourism

to this:

Bien Donné agri tourism

I am using the 'unescape' function published on
http://effbot.org/zone/re-sub.htm#unescape-html but working through a file
I get the following error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 519:
ordinal not in range(128)

and I do not now how to solve this problem.

Any solution will be very appriciated.

Regards
Johann

-- 
Because experiencing your loyal love is better than life itself,
my lips will praise you.  (Psalm 63:3)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting html character codes to utf-8 text

2012-06-19 Thread Peter Otten
Johann Spies wrote:

> I am trying the following:
> 
> Change data like this:
> 
> Bien Donné : agri tourism
> 
> to this:
> 
> Bien Donné agri tourism
> 
> I am using the 'unescape' function published on
> http://effbot.org/zone/re-sub.htm#unescape-html but working through a file
> I get the following error:
> 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 519:
> ordinal not in range(128)
> 
> and I do not now how to solve this problem.
> 
> Any solution will be very appriciated.

The information you give is not sufficient to give a fix, but my crystal 
ball says that the string you pass to unescape() contains an e with acute 
encoded in utf-8 and not as an html escape. Instead of 

unescape(mydata)

try

unescape(mydata.decode("utf-8"))

If that doesn't fix the problem come back with a self-contained example.



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


Re: Checking compatibility of a script across Python versions automatically

2012-06-19 Thread Steven D'Aprano
On Mon, 18 Jun 2012 14:24:03 -0500, Andrew Berg wrote:

> Are there any tools out there that will parse a script and tell me if it
> is compatible with an arbitrary version of Python and highlight any
> incompatibilities? I need to check a few of my scripts that target 3.2
> to see if I can make them compatible with 3.0 and 3.1 if they aren't
> already. I found pyqver, but it isn't accurate (at least for 3.2/3.3
> scripts) and hasn't been updated in 2 years. I could look over the docs
> and do it manually, but one of the scripts isn't small, so I'd prefer
> not to.

You could try running it and see if it breaks. That usually works for 
me :)

For anything except throw-away scripts, I prefer to write scripts with a 
"self-test" option so that I (or any other user) can run the test and see 
if it works without actually using it for production work.


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


Re: Is that safe to use ramdom.random() for key to encrypt?

2012-06-19 Thread Thomas Rachel

Am 18.06.2012 01:48 schrieb Paul Rubin:

Steven D'Aprano  writes:

/dev/urandom isn't actually cryptographically secure; it promises not to
block, even if it has insufficient entropy. But in your instance...


Correct. /dev/random is meant to be used for long-lasting
cryptographically-significant uses, such as keys. urandom is not.


They are both ill-advised if you're doing anything really serious.


Hm?


> In practice if enough entropy has been in the system to make a key with

/dev/random, then urandom should also be ok.


Right.


> Unfortunately the sensible

interface is missing: block until there's enough entropy, then generate
data cryptographically, folding in new entropy when it's available.


What am I missing? You exactly describe /dev/random's interface.


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


Re: Read STDIN as bytes rather than a string

2012-06-19 Thread Oscar Benjamin
On 19 June 2012 00:53, Jason Friedman  wrote:

> Which leads me to another question ... how can I debug these things?
>
> $ echo 'hello' | python3 -m pdb ~/my-input.py
> > /home/jason/my-input.py(2)()
> -> import sys
> (Pdb) *** NameError: name 'hello' is not defined
> --
> http://mail.python.org/mailman/listinfo/python-list
>

It's difficult to debug problems that are related to reading from stdin. I
don't know of any good way, so I just end up doing things like adding print
statements and checking the output rather than using a debugger. Tools like
hd can help with checking the input/output files that you're using. If
there were a debugger it would probably need to be one with a GUI - the
only one I know is spyder but I don't think that will allow you to pipe
anything on stdin.

One thing I wanted to say is that if your script is intended to work on
Windows you'll need to use msvcrt.setmode() to disable newline translation
on stdin (I haven't tested with Python 3.x, but it's definitely necessary
with Python 2.x). See Frazil's post here:
http://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic cross-platform GUI desingers à la Interface Builder (Re: what gui designer is everyone using)

2012-06-19 Thread Wolfgang Keller
> >> No matter how cool it may seem to create simple GUIs manually or to
> >> write business letters using LaTeX: just try to persuade people to
> >> move from Word to LaTeX for business letters...
> >
> > Good example.
> >
> > I have done nearly exactly this* - but it was only possible thanks
> > to LyX.
> 
> > *I moved not from Wugh, but from other software to LyX/LaTeX for
> > all my document processing.
> But of course, you were only doing so because you had LyX available,
> which is the equivalent of an easy-to-use GUI builder.

No need to argue here. This was exactly my point. :-)

> So maybe I should be more precise: just try to persuade people to move
> from Word to *pure* LaTeX for business letters...

Nearly impossible. And this was exactly my point. Again, no need to
argue here. :-)

The success of LyX (and TeXmacs and BaKoMaTeX and Scientific Word...)
proves imho that the LaTeX community had missed to offer a
"syntax-hiding"-GUI with LaTeX some 20 years ago.

And the lack of success of Python so far to replace, in your
application case, Labview, or, in my application case, all those
proprietary 4GL IDEs/frameworks/GUI builders (just check the success
that Realbasic has) proves imho that the Python community has totally
missed to address the vast crowd of potential users who are domain
experts in other domains than software development.

Sincerely,

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


Re: [Tutor] Pymongo Error

2012-06-19 Thread James Reynolds
On Tue, Jun 19, 2012 at 1:22 AM, Ranjith Kumar wrote:

> Hi all,
> I tried Django with Mongodb while running manage.py syncdb I endup with
> this error
>
> note : it works fine with sqlite and mysql db
>
> (django-1.3)ranjith@ranjith:~/
> sandbox/python-box/hukkster-core-site/hukk$ ./manage.py syncdb
> /home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/pymongo/connection.py:385:
> UserWarning: must provide a username and password to authenticate to
> hukkster_testing
>   "to authenticate to %s" % (db,))
> Creating tables ...
> Traceback (most recent call last):
>   File "./manage.py", line 14, in 
> execute_manager(settings)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
> line 438, in execute_manager
> utility.execute()
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
> line 379, in execute
> self.fetch_command(subcommand).run_from_argv(self.argv)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 191, in run_from_argv
> self.execute(*args, **options.__dict__)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 220, in execute
> output = self.handle(*args, **options)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 351, in handle
> return self.handle_noargs(**options)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py",
> line 109, in handle_noargs
> emit_post_sync_signal(created_models, verbosity, interactive, db)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/sql.py",
> line 190, in emit_post_sync_signal
> interactive=interactive, db=db)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py",
> line 172, in send
> response = receiver(signal=self, sender=sender, **named)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py",
> line 41, in create_permissions
> "content_type", "codename"
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 107, in _result_iter
> self._fill_cache()
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 772, in _fill_cache
> self._result_cache.append(self._iter.next())
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 959, in iterator
> for row in self.query.get_compiler(self.db).results_iter():
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 229, in results_iter
> for entity in self.build_query(fields).fetch(low_mark, high_mark):
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 290, in build_query
> query.order_by(self._get_ordering())
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 339, in _get_ordering
> raise DatabaseError("Ordering can't span tables on non-relational
> backends (%s)" % order)
> django.db.utils.DatabaseError: Ordering can't span tables on
> non-relational backends (content_type__app_label)
>
>
> DB settings in settings.py
>
> DATABASES = {
> 'default': {
> 'ENGINE': 'django_mongodb_engine',
> 'NAME': 'helloworld',
> 'USER': '',
> 'PASSWORD': '12424214',
> 'HOST': 'mongodb://staff.mongohq.com/',
> 'PORT': 'X',
> },
> }
>
> my requirement packages,
> Django==1.3
> dictshield==0.4.4
> django-mongodb-engine==0.4.0
> django-social-auth==0.6.9
> djangotoolbox==0.0.1
> httplib2==0.7.4
> mongoengine==0.6.10
> mongokit==0.8
> oauth2==1.5.211
> pymongo==2.2
> python-openid==2.2.5
> simplejson==2.5.2
> wsgiref==0.1.2
>
> Please point me what i missed here...
>
> --
> Cheers,
> Ranjith Kumar K,
> Chennai.
>
> http://ranjithtenz.wordpress.com
>
>
>
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


This list here is for new users to python. Using mongo with django is a
pretty advanced topic. I would suggest posting this on stackoverflow, or to
the django-users group (and there are a ton of resources on this already on
those two sites on this topic)

That said, having used mongo with django, I'll bet your problem is that you
are using the django version provided by the django pro

Re: [BangPypers] Help On Paramiko

2012-06-19 Thread satyaakam goswami
>
> o/p
> ['UNIX shell commands cannot be executed using this account.\n']
>
> Any suggestions?
>
>
last time i had such a requirement it started just like you into  writing
something , then i did a quick web search before starting and found
http://code.google.com/p/sshpt/ which served all our requirements so we
stuck to . it too uses paramiko.

-Satya
fossevents.in
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help On Paramiko

2012-06-19 Thread Michael Torrie
On 06/19/2012 12:28 AM, nikunj.badja...@emc.com wrote:
> Howdy All,
> 
> I am trying to use paramiko to automate logging in to remote unix machines 
> and executing some commands there.
> When I normally do ssh from my linux machine (with Python 2.6) to this 
> machine a different '>' prompt comes. It's a device specific custom prompt.
> After I run 'enable' command here, a new prompt opens up. '#' which is also 
> custom prompt.
> Then I need to run 'configure terminal' there. And then some more device 
> specific commands.

I think you want an abstraction layer like fabric, or the old and
venerable pexpect.  Makes this kind of interaction a lot easier.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter binding question

2012-06-19 Thread Frederic Rentsch
Rick, 

Thank you for your thorough discussion. I tried your little program.
Enter and leave work as expected. Pushing mouse buttons call
leave-enter, exactly as it happened with my code. So that seems to be a
default behavior. No big deal. Without the tracing messages it would go
unnoticed. Releasing either of the bound mouse buttons displays the
corresponding messages. So all works fine. 
   If I copy your event descriptors into my program, the button-release
callback still fails. It works in your code, not in mine. Here is what
my code now looks like. It is somewhat more complicated than yours,
because I bind Frames holding each a line (line_frame) and each frame
contains a few Labels side by side. The idea is to achieve a table with
vertically aligning columns each line of which I can click-select. (Is
there a better way?)

   for line_frame in ...:
  line_frame.bind ('', self.color_selected)
  line_frame.bind ('', self.color_selectable)
  line_frame.bind ('', self.pick_record)
  line_frame.bind ('', self.info_profile)
  line_frame.grid (row = n+1, column = 0)
  for i in self.range_n_fields:
 field = Label (line_frame, width = ..., text = ...
 field.grid (row = 0, column = i, sticky = W)
  ...

   def color_selected (self, event):
  print 'hit list.color_selected ()'

   def color_selectable (self, event):
  print 'hit list.color_selectable ()'

   def pick_record (self, event): # Nver gets called
  print 'hit list.pick_record ()'

   def info_profile (self, event):# Never gets called
  print 'hit list.info_profile ()'

I admit that I don't have an accurate conception of the inner workings.
It's something the traveler on the learning curve has to acquire a feel
for by trial and error. In this case the differing behavior should
logically have to do with the structural difference: I bind Labels that
contain Labels. If I click this nested assembly, who gets the event? The
contained widget, the containing widget or both?

Frederic


Incidentally, my source of inspiration for chaining event descriptors
was the New Mexico Tech Tkinter 8.4 reference, which says: ... In
general, an event sequence is a string containing one or more event
patterns. Each event pattern describes one thing that can happen. If
there is more than one event pattern in a sequence, the handler will be
called only when all the patterns happen in that same sequence ...

Again, predicting the precedence with overlaps is much like solving a
murder case: finding suspects and let the innocent ones off the hook.
The only reference I have found on that topic is in effbot.org's
tkinterbook, which says that precedence goes to the "closest match", but
doesn't explain how one evaluates "closeness".


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


Python equivalent to the "A" or "a" output conversions in C

2012-06-19 Thread Edward C. Jones

Consider the following line in C:
   printf('%a\n', x);
where x is a float or double.  This outputs a hexadecimal representation 
of x.  Can I do this in Python?


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


Re: Python equivalent to the "A" or "a" output conversions in C

2012-06-19 Thread Hemanth H.M
Are you looking for :

>>> x=10
>>> hex(x)
'0xa'
>>> x=10.5
>>> float.hex(x)
'0x1.5p+3'

On Tue, Jun 19, 2012 at 9:53 PM, Edward C. Jones wrote:

> hexadecimal




-- 
*'I am what I am because of who we all are'*
h3manth.com 
*-- Hemanth HM *
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivalent to the "A" or "a" output conversions in C

2012-06-19 Thread Alexander Blinne
On 19.06.2012 18:23, Edward C. Jones wrote:
> Consider the following line in C:
>printf('%a\n', x);
> where x is a float or double.  This outputs a hexadecimal representation
> of x.  Can I do this in Python?

Don't know why there is no format character %a or %A in python, but the
conversion is done by float method hex():

a = 3.1415
print a.hex()

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


Re: Python equivalent to the "A" or "a" output conversions in C

2012-06-19 Thread Mark Lawrence

On 19/06/2012 17:23, Edward C. Jones wrote:

Consider the following line in C:
printf('%a\n', x);
where x is a float or double. This outputs a hexadecimal representation
of x. Can I do this in Python?



See this http://docs.python.org/library/string.html#format-examples

--
Cheers.

Mark Lawrence.

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


Finding absolute path of imported module?

2012-06-19 Thread Roy Smith
We're trying to debug a weird (and, of course, intermittent) problem a
gunicorn-based web application.  Our production directory structure
looks like:

deploy/
  rel-2012-06-14/
  rel-2012-06-12/
  rel-2012-06-11/
  current -> rel-2012006-14

Each time we deploy a new version, we create a new release directory,
move the "current" symlink, and restart gunicorn.  We've seen
instances where some of the workers end up importing some modules from
one directory and some from another (i.e. the old and new targets of
current).

So, the question is, is there any way to dump all the *absolute*
pathnames of all the imported modules?  I can iterate over
sys.modules.values(), but that doesn't give me absolute pathnames, so
I can't tell which version of the symlink existed when the module was
imported.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding absolute path of imported module?

2012-06-19 Thread Christian Heimes
Am 19.06.2012 19:55, schrieb Roy Smith:
> So, the question is, is there any way to dump all the *absolute*
> pathnames of all the imported modules?  I can iterate over
> sys.modules.values(), but that doesn't give me absolute pathnames, so
> I can't tell which version of the symlink existed when the module was
> imported.

You can use os.path.abspath(module.__file__) to get the absolute path of
a module. This works reliable unless you use os.chdir() in your code.

abspath() may not normalize symlinks (not sure about it) but you can
check for symlink with os.path.islink() (uses os.lstat) and resolve the
link with os.readlink().

Christian

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


Re: Python equivalent to the "A" or "a" output conversions in C

2012-06-19 Thread Edward C. Jones

On 06/19/2012 12:41 PM, Hemanth H.M wrote:


>>> float.hex(x)
'0x1.5p+3'

Some days I don't ask the brightest questions.  Suppose x was a numpy 
floating scalar (types numpy.float16, numpy.float32, numpy.float64, or 
numpy.float128).  Is there an easy way to write x in

binary or hex?



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


Re: Python equivalent to the "A" or "a" output conversions in C

2012-06-19 Thread jmfauth
On Jun 19, 9:54 pm, "Edward C. Jones"  wrote:
> On 06/19/2012 12:41 PM, Hemanth H.M wrote:
>
> > >>> float.hex(x)
> > '0x1.5p+3'
>
> Some days I don't ask the brightest questions.  Suppose x was a numpy
> floating scalar (types numpy.float16, numpy.float32, numpy.float64, or
> numpy.float128).  Is there an easy way to write x in
> binary or hex?

I'm not aware about a buitin fct. May be the module
struct — Interpret bytes as packed binary data can help.

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


Re: "constant sharing" works differently in REPL than in script ?

2012-06-19 Thread shearichard
Thanks for all the replies. I hadn't thought about the opportunities that exist 
for optimization when the whole script is there (or when compound operations 
are taking place) by contrast with plain old REPL ops.

I liked your code Chris demoing the different ranges in different versions. I 
tried to write something like that myself but you did it an awful lot better !

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


Re: "constant sharing" works differently in REPL than in script ?

2012-06-19 Thread Chris Angelico
On Wed, Jun 20, 2012 at 7:21 AM,   wrote:
> I liked your code Chris demoing the different ranges in different versions. I 
> tried to write something like that myself but you did it an awful lot better !

There's no guarantee that it'll prove which are and aren't cached, but
it does seem to work. (Incidentally, it doesn't handle the case where
_no_ integers are cached.)

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


Re: Finding absolute path of imported module?

2012-06-19 Thread Gelonida N

On 06/19/2012 09:32 PM, Christian Heimes wrote:

Am 19.06.2012 19:55, schrieb Roy Smith:

So, the question is, is there any way to dump all the *absolute*
pathnames of all the imported modules?  I can iterate over
sys.modules.values(), but that doesn't give me absolute pathnames, so
I can't tell which version of the symlink existed when the module was
imported.


You can use os.path.abspath(module.__file__) to get the absolute path of
a module. This works reliable unless you use os.chdir() in your code.

abspath() may not normalize symlinks (not sure about it) but you can
check for symlink with os.path.islink() (uses os.lstat) and resolve the
link with os.readlink().

If I remember well, os.path.realpath(module.__file__) should normalize 
the paths and resolve the symlinks


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


Re: Py3.3 unicode literal and input()

2012-06-19 Thread Steven D'Aprano
On Mon, 18 Jun 2012 07:00:01 -0700, jmfauth wrote:

> On 18 juin, 12:11, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
>> On Mon, 18 Jun 2012 02:30:50 -0700, jmfauth wrote:
>> > On 18 juin, 10:28, Benjamin Kaplan  wrote:
>> >> The u prefix is only there to
>> >> make it easier to port a codebase from Python 2 to Python 3. It
>> >> doesn't actually do anything.
>>
>> > It does. I shew it!
>>
>> Incorrect. You are assuming that Python 3 input eval's the input like
>> Python 2 does. That is wrong. All you show is that the one-character
>> string "a" is not equal to the four-character string "u'a'", which is
>> hardly a surprise. You wouldn't expect the string "3" to equal the
>> string "int('3')" would you?
>>
>> --
>> Steven
> 
> 
> A string is a string, a "piece of text", period.
> 
> I do not see why a unicode literal and an (well, I do not know how the
> call it) a "normal class " should behave differently in code source
> or as an answer to an input().

They do not. As you showed earlier, in Python 3.3 the literal strings 
u'a' and 'a' have the same meaning: both create a one-character string 
containing the Unicode letter LOWERCASE-A.

Note carefully that the quotation marks are not part of the string. They 
are delimiters. Python 3.3 allows you to create a string by using 
delimiters:

' '
" "
u' '
u" "

plus triple-quoted versions of the same. The delimiter is not part of the 
string. They are only there to mark the start and end of the string in 
source code so that Python can tell the difference between the string "a" 
and the variable named "a".

Note carefully that quotation marks can exist inside strings:

my_string = "This string has 'quotation marks'."

The " at the start and end of the string literal are delimiters, not part 
of the string, but the internal ' characters *are* part of the string.

When you read data from a file, or from the keyboard using input(), 
Python takes the data and returns a string. You don't need to enter 
delimiters, because there is no confusion between a string (all data you 
read) and other programming tokens.

For example:

py> s = input("Enter a string: ")
Enter a string: 42
py> print(s, type(s))
42 

Because what I type is automatically a string, I don't need to enclose it 
in quotation marks to distinguish it from the integer 42.

py> s = input("Enter a string: ")
Enter a string: This string has 'quotation marks'.
py> print(s, type(s))
This string has 'quotation marks'. 


What you type is exactly what you get, no more, no less.

If you type 42, you get the two character string "42" and not the int 42.

If you type [1, 2, 3], then you get the nine character string "[1, 2, 3]" 
and not a list containing integers 1, 2 and 3.

If you type 3**0.5 then you get the six character string "3**0.5" and not 
the float 1.7320508075688772.

If you type u'a' then you get the four character string "u'a'" and not 
the single character 'a'.

There is nothing new going on here. The behaviour of input() in Python 3, 
and raw_input() in Python 2, has not changed.


> Should a user write two derived functions?
> 
> input_for_entering_text()
> and
> input_if_you_are_entering_a_text_as_litteral()

If you, the programmer, want to force the user to write input in Python 
syntax, then yes, you have to write a function to do so. input() is very 
simple: it just reads strings exactly as typed. It is up to you to 
process those strings however you wish.



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


Re: Tkinter binding question

2012-06-19 Thread rantingrickjohnson
On Tuesday, June 19, 2012 10:55:48 AM UTC-5, Frederic Rentsch wrote:
> If I copy your event descriptors into my program, the button-release
> callback still fails. It works in your code, not in mine. Here is what
> my code now looks like. It is somewhat more complicated than yours,
> because I bind Frames holding each a line (line_frame) and each frame
> contains a few Labels side by side. The idea is to achieve a table with
> vertically aligning columns each line of which I can click-select. (Is
> there a better way?)
> 
>for line_frame in ...:
>   line_frame.bind ('', self.color_selected)
>   line_frame.bind ('', self.color_selectable)
>   line_frame.bind ('', self.pick_record)
>   line_frame.bind ('', self.info_profile)
>   line_frame.grid (row = n+1, column = 0)
>   for i in self.range_n_fields:
>  field = Label (line_frame, width = ..., text = ...
>  field.grid (row = 0, column = i, sticky = W)
>   ...
> 
>def color_selected (self, event):
>   print 'hit list.color_selected ()'
> 
>def color_selectable (self, event):
>   print 'hit list.color_selectable ()'
> 
>def pick_record (self, event): # Nver gets called
>   print 'hit list.pick_record ()'
> 
>def info_profile (self, event):# Never gets called
>   print 'hit list.info_profile ()'

Events only fire for the widget that currently has "focus". Frames, labels, and 
other widgets do not receive focus simply by hovering over them. You can set 
the focus manually by calling "w.focus_set()" -- where "w" is any Tkinter 
widget. I can't be sure because i don't have enough of your code to analyze, 
but I think you should bind (either globally or by class type) all "Enter" 
events to a callback that sets the focus of the current widget under the mouse. 
Experiment with this code and see if it is what you need:

## START CODE ##
from __future__ import print_function
import Tkinter as tk

def cb(event):
print(event.widget.winfo_class())
event.widget.focus_set()

root = tk.Tk()
root.geometry('200x200+20+20')
for x in range(10):
w = tk.Frame(root, width=20, height=20,bg='red')
w.grid(row=x, column=0, padx=5, pady=5)
w = tk.Frame(root, width=20, height=20,bg='green', highlightthickness=1)
w.grid(row=x, column=1, padx=5, pady=5)
w = tk.Button(root, text=str(x))
w.grid(row=x, column=2, padx=5, pady=5)
root.bind_all("", cb)
root.mainloop()
## END CODE ##

You will see that the first column of frames are recieving focus but you have 
no visual cues of that focus (due to a default setting). In the second column 
you get the visual cue since i set "highlightthicness=1". The third column is a 
button widget which by default has visual focus cues.

Is this the problem? 

PS: Also check out the "w.bind_class()" method.

> Incidentally, my source of inspiration for chaining event descriptors
> was the New Mexico Tech Tkinter 8.4 reference, 

That's an excellent reference BTW. Keep it under your pillow. Effbot also has a 
great tutorial.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivalent to the "A" or "a" output conversions in C

2012-06-19 Thread Aldrich DeMata
Use the binascii module:

>>> import numpy as np
>>> x = np.float32(3.14)
>>> x.dtype
dtype('float32')
>>> binascii.hexlify(x)
'c3f54840'

The final result is little endian so it should be read as 0x4048f5c3
instead.

You can verify the conversion using the link below:
http://gregstoll.dyndns.org/~gregstoll/floattohex/

aldrich

On Tue, Jun 19, 2012 at 2:54 PM, Edward C. Jones wrote:

> On 06/19/2012 12:41 PM, Hemanth H.M wrote:
>
>  >>> float.hex(x)
>> '0x1.5p+3'
>>
>>  Some days I don't ask the brightest questions.  Suppose x was a numpy
> floating scalar (types numpy.float16, numpy.float32, numpy.float64, or
> numpy.float128).  Is there an easy way to write x in
> binary or hex?
>
>
>
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list