Why can't I set sys.ps1 to a unicode string?

2010-08-11 Thread RG
More precisely, why does sys.ps1 not appear if I set it to a unicode 
string?  This problem is hard for me to describe here because my 
newsreader is not properly unicode enabled, but here's the gist of it:

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

First, let's make sure our encodings are set properly:

>>> import sys
>>> sys.stdin.encoding
'utf-8'
>>> sys.stdout.encoding
'utf-8'

Looks good.  Now, let's make two unicode strings, identical except for 
one character:

>>> s1 = u'%%% %%% '
>>> s2 = u'%%% ' + u'\u262f' + '%%% '
>>> print s1
%%% %%% 
>>> print s2
%%% /&%%% 

If this were a properly unicode-enabled newsreader you would see a 
yin-yang symbol in the middle of s2.

Now the weird part:

>>> sys.ps1 = s1
%%% %%% sys.ps1 = s2   # This is as expected
print s1   # But this isn't.  There's no prompt!
%%% %%%# Everything still works
print s2
%%% /&%%% 
sys.ps1 = s1   # If we reset sys.ps1 we get our prompt back
%%% %%% sys.ps1 = '>>> '
>>> sys.ps1 = u'>>> '
>>> 

So... why does having a non-ascii character in sys.ps1 make the prompt 
vanish?

(If you're wondering why I care, I want to connect to an interactive 
python interpreter from another program, and I want a non-ascii 
delimiter to unambiguously mark the end of the interpreter's output on 
every interaction.)

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


Beyond the moratorium

2010-08-11 Thread Vito 'ZeD' De Tullio
Hi all.

I know, maybe I'm just lazily speculating, but I'm curious about what's 
next, in python, when GvR will stop the moratorium and will let changes in 
the language.

I don't know what to expect... some syntax sugar about concurrent 
programming? static types? an erlang-style "bang" (!) process message 
passing?

-- 
By ZeD

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


Re: urllib2 does not implement "with" Python 2.6

2010-08-11 Thread Paul Rubin
John Nagle  writes:
> "AttributeError: addinfourl instance has no attribute '__exit__'".
>
> I thought that all the file-like objects supported "with" in 2.6.
> No?

I guess not.  Use contextlib.closing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does Python get the value for sys.stdin.encoding?

2010-08-11 Thread RG
In article ,
 Benjamin Kaplan  wrote:

> On Wed, Aug 11, 2010 at 6:21 PM, RG  wrote:
> > I thought it was hard-coded into the Python executable at compile time,
> > but that is apparently not the case:
> >
> > [...@mickey:~]$ python
> > Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
> > [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.
>  import sys;print sys.stdin.encoding
> > UTF-8
>  ^D
> > [...@mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python
> > None
> > [...@mickey:~]$
> >
> > And indeed, trying to pipe unicode into Python doesn't work, even though
> > it works fine when Python runs interactively.  So how can I make this
> > work?
> >
> 
> Sys.stdin and stdout are files, just like any other. There's nothing
> special about them at compile time. When the interpreter starts, it
> checks to see if they are ttys. If they are, then it tries to figure
> out the terminal's encoding based on the environment. The code for
> this is in pythonrun.c if you want to see exactly what it's doing.

Thanks.  Looks like the magic incantation is:

export PYTHONIOENCODING='utf-8'

> By the way, there is no such thing as piping Unicode into Python.

Yeah, I know.  I should have said "piping UTF-8 encoded unicode" or 
something like that.

> You really have to watch your encodings
> when you pass data around between programs. There's no way to avoid
> it.

Yeah, I keep re-learning that lesson again and again.

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


urllib2 does not implement "with" Python 2.6

2010-08-11 Thread John Nagle

  Somewhat to my surprise, in Python 2.6,

with urllib2.urlopen(url) as fh :

doesn't work.  It fails with
"AttributeError: addinfourl instance has no attribute '__exit__'".

I thought that all the file-like objects supported "with" in 2.6.
No?

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


Re: favicon.ico problem

2010-08-11 Thread Gabriel Genellina
En Tue, 10 Aug 2010 01:32:49 -0300, Navkirat Singh   
escribió:


I am having this strange problem. I have programmed a very basic  
multiprocessing webserver using low level sockets. Each time the server  
receives a request it spawns a new process to handle the request. Now  
when through a web browser I type http://localhost:8001/ it  
automatically creates two processes: One process to server the '/' path  
and another one to serve the '/favicon.ico' path. I have not programmed  
it to serve the latter. Infact I dont even know where that name  
'/favicon.ico' comes from. Any insight into this weird behavior would be  
greatly appreciated.


It't the browser attempting to get an icon for the page.
See http://en.wikipedia.org/wiki/Favicon

--
Gabriel Genellina

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


Re: How to capture all the environment variables from shell?

2010-08-11 Thread Cameron Simpson
On 12Aug2010 01:28, Nobody  wrote:
| On Wed, 11 Aug 2010 13:08:59 +1000, Cameron Simpson wrote:
| > The reason .bashrc gets overused for envars, aside from ignorance and
| > propagated bad habits, is that in a GUI desktop the setup sequence is
| > often a bit backwards. A conventional terminal/console login means you
| > get a login shell that sources your .{bash_}profile. And from there one
| > would start a GUI and all the .profile stuff has been run Once, as it
| > should be. But when the login itself is a GUI the various terminals get
| > started _before_ the .profile stuff gets sourced, because the terminal
| > is started by the desktop manager. Once common "fix" for this is to
| > make all new terminals run login shells. Ugh, but it does work.
| 
| Er, not really. If you don't source your ~/.profile (etc) from e.g.
| ~/.xsession, GUI applications don't get to see the environment settings
| therein. The environment isn't just for shells.

I think we're in violent agreement here. I arrange to do exactly that in
my own desktop setups.

However, the ones that ship with distros generally don't, possibly because a
shell-aborting error in the .profile (or unwanted interaction etc) will abort
the GUI login/desktop-setup.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

The Puritan hated bear-baiting, not because it gave pain to the bear, but
because it gave pleasure to the spectator. - Macaulay, History of England
-- 
http://mail.python.org/mailman/listinfo/python-list


globbal | creating networks

2010-08-11 Thread apustilnik
Hi, i'd like to invite you to know this new way to keep in touch with
friends, and meet new people!
http://www.globbal.com.ar/login1.php
Invite your friends to join, and start creating your own globbal
networks!
Are you ready to live a new experience?
Are you ready to live globbal!
Sign up now!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does Python get the value for sys.stdin.encoding?

2010-08-11 Thread Benjamin Kaplan
On Wed, Aug 11, 2010 at 6:21 PM, RG  wrote:
> I thought it was hard-coded into the Python executable at compile time,
> but that is apparently not the case:
>
> [...@mickey:~]$ python
> Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
> [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
 import sys;print sys.stdin.encoding
> UTF-8
 ^D
> [...@mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python
> None
> [...@mickey:~]$
>
> And indeed, trying to pipe unicode into Python doesn't work, even though
> it works fine when Python runs interactively.  So how can I make this
> work?
>

Sys.stdin and stdout are files, just like any other. There's nothing
special about them at compile time. When the interpreter starts, it
checks to see if they are ttys. If they are, then it tries to figure
out the terminal's encoding based on the environment. The code for
this is in pythonrun.c if you want to see exactly what it's doing. If
stdout and stdin aren't ttys, then their encoding stays as None and
the interpreter will use sys.getdefaultencoding() if you try printing
Unicode strings.

By the way, there is no such thing as piping Unicode into Python.
Unicode is an abstract concept where each character maps to a
codepoint. Pipes can only deal with bytes. You may be using one of the
5 encodings capable of holding the entire range of Unicode characters
(UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE, and UTF-32 BE), but that's
not the same thing as Unicode. You really have to watch your encodings
when you pass data around between programs. There's no way to avoid
it.
-- 
http://mail.python.org/mailman/listinfo/python-list


python ide for ubuntu

2010-08-11 Thread Bhanu Kumar
Hi All,

Is there any good free python IDE available in Ubuntu?


thanks,
-Bhanu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread RG
In article ,
 Nobody  wrote:

> On Wed, 11 Aug 2010 10:32:41 +, Tim Harig wrote:
> 
> >>> Usually you either
> >>> need an option on the upstream program to tell it to line
> >>> buffer explicitly
> >>
> >> once cat had an option -u doing exactly that but nowadays
> >> -u seems to be ignored
> >>
> >> http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html
> > 
> > I have to wonder why cat knows or cares.
> 
> The issue relates to the standard C library. By convention[1], stdin and
> stdout are line-buffered if the descriptor refers to a tty, and are
> block-buffered otherwise. stderr is always unbuffered.
> 
> Any program which uses stdin and stdout without explicitly setting the
> buffering or using fflush() will exhibit this behaviour.
> 
> [1] ANSI/ISO C is less specific; C99, 7.19.3p7:
> 
>   As initially opened, the standard error stream is not fully
>   buffered; the standard input and standard output streams are
>   fully buffered if and only if the stream can be determined not
>   to refer to an interactive device.
> 
> POSIX says essentially the same thing:
> 
> 

This doesn't explain why "cat | cat" when run interactively outputs 
line-by-line (which it does).  STDIN to the first cat is a TTY, but the 
second one isn't.

For that matter, you can also do this:

nc -l 1234 | cat

and then telnet localhost 1234 and type at it, and it still works 
line-by-line.

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


Deer Esurance

2010-08-11 Thread Carl Banks
If you're going to send me unsolicited email, the least you can do it
include pics of Erin.

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


How does Python get the value for sys.stdin.encoding?

2010-08-11 Thread RG
I thought it was hard-coded into the Python executable at compile time, 
but that is apparently not the case:

[...@mickey:~]$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys;print sys.stdin.encoding
UTF-8
>>> ^D
[...@mickey:~]$ echo 'import sys;print sys.stdin.encoding' | python
None
[...@mickey:~]$

And indeed, trying to pipe unicode into Python doesn't work, even though 
it works fine when Python runs interactively.  So how can I make this 
work?

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


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread Nobody
On Wed, 11 Aug 2010 10:32:41 +, Tim Harig wrote:

>>> Usually you either
>>> need an option on the upstream program to tell it to line
>>> buffer explicitly
>>
>> once cat had an option -u doing exactly that but nowadays
>> -u seems to be ignored
>>
>> http://www.opengroup.org/onlinepubs/009695399/utilities/cat.html
> 
> I have to wonder why cat knows or cares.

The issue relates to the standard C library. By convention[1], stdin and
stdout are line-buffered if the descriptor refers to a tty, and are
block-buffered otherwise. stderr is always unbuffered.

Any program which uses stdin and stdout without explicitly setting the
buffering or using fflush() will exhibit this behaviour.

[1] ANSI/ISO C is less specific; C99, 7.19.3p7:

As initially opened, the standard error stream is not fully
buffered; the standard input and standard output streams are
fully buffered if and only if the stream can be determined not
to refer to an interactive device.

POSIX says essentially the same thing:



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


Re: How to capture all the environment variables from shell?

2010-08-11 Thread Nobody
On Wed, 11 Aug 2010 13:08:59 +1000, Cameron Simpson wrote:

> The reason .bashrc gets overused for envars, aside from ignorance and
> propagated bad habits, is that in a GUI desktop the setup sequence is
> often a bit backwards. A conventional terminal/console login means you
> get a login shell that sources your .{bash_}profile. And from there one
> would start a GUI and all the .profile stuff has been run Once, as it
> should be. But when the login itself is a GUI the various terminals get
> started _before_ the .profile stuff gets sourced, because the terminal
> is started by the desktop manager. Once common "fix" for this is to
> make all new terminals run login shells. Ugh, but it does work.

Er, not really. If you don't source your ~/.profile (etc) from e.g.
~/.xsession, GUI applications don't get to see the environment settings
therein. The environment isn't just for shells.

The reason why ~/.profile is only sourced by login shells is that it's
supposed to be sourced exactly once, by the initial process of a session,
i.e. the one from which all other programs descend. For a terminal-based
login, "login" (or sshd or whatever) starts the shell as a login shell
(with argv[0][0] == '-'), and the shell sets up the environment.

For a desktop login, there is no login shell, so something else has to set
up the environment. Simple enough; well, simple enough for anyone who
understands Unix, processes, sessions, etc. But apparently too complex for
the people who create desktop environments, who seem to think that the
environment is somehow specific to shells.

So you usually need to manually configure your session script (e.g.
~/.xsession for xdm) to set up the environment before the desktop
environment gets a look-in.

One caveat: if you set LD_LIBRARY_PATH, it will be unset when running a
setuid or setgid program. This is sometimes the case for terminal
emulators[1], in which case you need to have ~/.bashrc reinstate the
setting.

[1] Allocating a BSD-style pty requires root privilege, and writing
utmp/wtmp entries requires write permission on the file. Modern systems
have Unix98 ptys and a setgid helper program to manage the utmp/wtmp
entries, so there shouldn't be any need for xterm etc to be setuid or
setgid nowadays.

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


Re: GUI automation tool (windows)

2010-08-11 Thread Ben Finney
Alex Barna  writes:

> I know that this question has been asked for several times,
[…]

> So what happens to this field (Windows GUI automation [with Python]) ?

Alex Barna  writes:

> It makes me doubt: is Python the correct language to do GUI
> automation ?

Your questions are definitely on-topic here. However, you might want to
make use of the “testing-in-python” forum
http://lists.idyll.org/listinfo/testing-in-python> where your
questions are even *more* on-topic :-)

-- 
 \  “We are stuck with technology when what we really want is just |
  `\ stuff that works.” —Douglas Adams |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: most popular gui framework for python

2010-08-11 Thread Ben Finney
Back9  writes:

> Does anyone know of what is the most popular gui framework for python
> application?

The Python standard library comes with one, Tkinter
http://docs.python.org/library/tkinter.html>.

Recently the Tix extension is also available in the standard library
http://docs.python.org/library/tix.html> bringing much richer and
better-looking widgets to Tk.

-- 
 \  “Dvorak users of the world flgkd!” —Kirsten Chevalier, |
  `\rec.humor.oracle.d |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft lessening commitment to IronPython and IronRuby

2010-08-11 Thread Ben Finney
Jason Earl  writes:

> Which is more of a promise than Microsoft has given to Python. I am
> not arguing for Mono, as I am not a fan. But if you honestly think
> that Python doesn't infringe on some of Microsoft's patents you are
> crazy.

It's quite true that anyone can be sued, at any time, for anything. And
any program can, because of the crazy patent system in many countries,
be infringing any (usually large) number of software idea patent claims,
without the programmers having done anything unusual to cause that
situation.

Microsoft, or any other party for that matter, very well may have any
number of software idea patents that could be interpreted to cover
Python's code.

The main difference in the case of Mono is that Microsoft has widely and
repeatedly asserted that such patents do exist, their assertions seem
quite plausible since they wrote the specifications on which Mono is
implemented, its “Community Promise” very carefully does *not* grant any
kind of binding permission to implement or use software ideas from those
patents, and it has consistently wielded other such patents aggressively
and maintains the willingness to continue to do so.

None of that is true for Python. Which is why people aren't saying
Python is a patent trap, but rather that Mono is.

-- 
 \“Most people, I think, don't even know what a rootkit is, so |
  `\ why should they care about it?” —Thomas Hesse, Sony BMG, 2006 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Tkinter Simple Qn

2010-08-11 Thread ChrisChia
Hi i have the following problem with Python Tkinter.
I switch to switch the image background (which i used Tkinter.Label
with image arg to display on the GUI).

How can I do that? the callback function which i have created doesn't
seem to work...
some advice?

below is my code:


import Tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()

# having problem with switching the image
def callback(event):
global root
root.panel1.pack_forget()
root.panel1.image = image2
root.panel1.pack()


def app():

root.title('FIT 2022 Assignment 1')

# pick an image file you have .bmp .jpg .gif. .png
# load the file and covert it to a Tkinter image object
imageFile = "c:\\test1.jpg"
image1 = ImageTk.PhotoImage(Image.open(imageFile))
imageFile2 = "c:\\test2.jpg"
image2 = ImageTk.PhotoImage(Image.open(imageFile2))


# get the image size
w = image1.width()
h = image1.height()


# position coordinates of root 'upper left corner'
x = 0
y = 0


# make the root window the size of the image
root.geometry("%dx%d+%d+%d" % (w, h, x, y))


# root has no image argument, so use a label as a panel
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')
panel1.image = image1
panel1.bind("", callback)


panel1.pack()
root.mainloop()


app()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urgent requirement at Hyderabad

2010-08-11 Thread Steven D'Aprano
On Wed, 11 Aug 2010 14:25:08 -0700, Emile van Sebille wrote:

> On 8/11/2010 12:39 PM MRAB said...
>> Stefan Behnel wrote:
>>> In case anyone wondered: Hyderabad is likely referring to some place
>>> in Asia:
>>>
>>> http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29
>>>
>> And Berlin is likely some place in Europe:
>>
>> http://en.wikipedia.org/wiki/Berlin_(disambiguation)
>>
>> :-)
> 
> And Paris is likely someplace in the US...
> 
> http://en.wikipedia.org/wiki/Paris_%28disambiguation%29

No, I'm pretty sure it's a town in Australia filled with murderers...

http://en.wikipedia.org/wiki/The_Cars_That_Ate_Paris





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


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-11 Thread Steven D'Aprano
On Wed, 11 Aug 2010 13:14:35 -0700, Baba wrote:

> level: beginner
> 
> exercise: given that packs of McNuggets can only be bought in 6, 9 or 20
> packs, write an exhaustive search to find the largest number of
> McNuggets that cannot be bought in exact quantity.

Is this a trick question?

I'd like to see somebody try to buy exactly 10**100**100 (1 googleplex) 
McNuggets. And that's not even close to the largest number that you can't 
buy.


Unhelpfully yours,


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


Re: Win7. Why Don't Matplotlib, ... Show up in Control Panel Add-Remove?

2010-08-11 Thread Giacomo Boffi
"Martin v. Loewis"  writes:

> If you use the bdist_wininst, bdist_msi, or bdist_rpm distutils
> commands, you get packages which support uninstallations very well.

bdist_deb?
-- 
Vorrei andare a lavorare in Sicilia, a max 15 km dal mare. Con chi 
devo parlare? Col capomafia distrettuale? Oppure bisogna sporcarsi le 
mani e fare la tessera di FI?  -- Marvin,  in IFQ
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: segfault with small pyqt script

2010-08-11 Thread Gelonida
Jusy FYI:

I made further tests and can crash the python script even if I delete
the linesassigning strings  to variables a to f

On 08/12/2010 01:07 AM, Gelonida wrote:
> Hi Guys,
> I'm desperate. I'm having a real application, which fails rather often
> when finishing it. I'm not sure, whether any serious problem could be
> hidden behind it
> 
> The script is a pyqt script, which segfaults most of the time on my
> ubuntu 10.4 linux 64 bit and I'm having trouble to understand why.
> 
> Trying to create the smallest possible test case I ended up with
> following script, which I named dodo.py and which i made executable with
> chmod +x ./dodo.py
> 
> #!/usr/bin/env python
> from PyQt4.QtGui import
> QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication
> a = "one"
> b = "unused"
> c = "also unused"
> d= "ans also unused"
> e = "another var"
> f = "something"
> class MyForm(QDialog):
> def __init__(self,parent=None,config=None,ini_info=None):
> super(MyForm,self).__init__(parent=parent)
> grid = QGridLayout()
> quit_btn = QPushButton("Quit")
> quit_btn.clicked.connect(self.quit)
> grid.addWidget(quit_btn,0,0)
> name = "a_name"
> vals_box = QComboBox()
> vals_box.addItem("one")
> vals_box.addItem("two")
> grid.addWidget(vals_box,0,1)
> self.setLayout(grid)
> def quit(self):
> self.close()
> if __name__ == "__main__":
> app = QApplication([])
> myform = MyForm()
> myform.show()
> retcode = app.exec_()
> print "last"
> 
> 
> 
> In order to perform the test several times I typed on the command line:
> 
> a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done
> 
> As soon as the window shows up
> I click twice (slowly ) on 'one' and then on quit.
> 
> Sample output can be seen here:
> gelon...@mypc:/my/directory$ a="" ; while [ "$a" = "" ] ; do ./dodo.py ;
> read -t 1 a ; done
> last
> last
> Segmentation fault
> last
> last
> Segmentation fault
> last
> Segmentation fault
> last
> Segmentation fault
> last
> last
> last
> last
> last
> Segmentation fault
> last
> last
> Segmentation fault
> last
> Segmentation fault
> 
> 
> as you see the segfault happens rather often.
> 
> Does anybody see something suspicious with my code?
> Can anybody else reproduce this?
> as soon as I remove more lines the error seems to disappear.
> 
> What else could I do to debug this issue?
> 
> thanks for help or other ideas
> 
> 
> 
> If I run my script with strace ./dodo.py
> I get following last lines for a run without error
>> rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f65d6b3b8f0}, {0x4d9820, 
>> [], SA_RESTORER, 0x7f65d6b3b8f0}, 8) = 0
>> munmap(0x7f65c6344000, 622280)  = 0
>> brk(0x2d71000)  = 0x2d71000
>> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, 
>> revents=POLLIN|POLLOUT}])
>> read(7, 
>> "\22\0\233\6\2\0\300\5\2\0\300\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"...,
>>  4096) = 384
>> writev(7, 
>> [{"\232\7\2\0\210\0\300\0056\0\2\0\207\0\300\5<\0\2\0\211\0\300\5\232\7\2\0s\0\300\5"...,
>>  540}, {NULL, 0}, {"", 0}], 3) = 540
>> poll([{fd=7, events=POLLIN}], 1, -1)= 1 ([{fd=7, revents=POLLIN}])
>> read(7, 
>> "\34\0\241\6r\0\300\5\234\1\0\0\377\261\220\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"...,
>>  4096) = 1472
>> read(7, 0x29fa704, 4096)= -1 EAGAIN (Resource temporarily 
>> unavailable)
>> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}])
>> writev(7, [{"O\7\2\0\1\0\300\5<\0\2\0\0\0\300\5+\0\1\0", 20}, {NULL, 0}, 
>> {"", 0}], 3) = 20
>> poll([{fd=7, events=POLLIN}], 1, -1)= 1 ([{fd=7, revents=POLLIN}])
>> read(7, 
>> "\1\2\333\6\0\0\0\0\5\0\300\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 
>> 4096) = 32
>> read(7, 0x29fa704, 4096)= -1 EAGAIN (Resource temporarily 
>> unavailable)
>> close(7)= 0
>> write(19, "\1\v\3\200\1\0\0\0\0\0\0\0\t\0\0\0", 16) = 16
>> close(19)   = 0
>> open("/proc/stat", O_RDONLY|O_CLOEXEC)  = 7
>> read(7, "cpu  59482 54 13580 7506040 4761"..., 8192) = 2439
>> close(7)= 0
>> writev(15, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12
>> close(15)   = 0
>> writev(13, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12
>> close(13)   = 0
>> close(12)   = 0
>> close(11)   = 0
>> unlink("/tmp/orbit-klausf/linc-1282-0-6094bc6991603") = 0
>> close(14)   = 0
>> write(6, "@", 1)= 1
>> close(6)= 0
>> close(5)= 0
>> rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_NOCLDSTOP, 
>> 0x7f65d6b3b8f0}, {0x7f65d40a3860, [], SA_RESTORER|SA_NOCLDSTOP, 
>> 0x7f65d6b3b8f0}, 8) = 0
>> exit_group(0)   
> 
> 
> and following when an error occurs:
>> writev(16, 
>> [{"<\10\2\0;\

segfault with small pyqt script

2010-08-11 Thread Gelonida
Hi Guys,
I'm desperate. I'm having a real application, which fails rather often
when finishing it. I'm not sure, whether any serious problem could be
hidden behind it

The script is a pyqt script, which segfaults most of the time on my
ubuntu 10.4 linux 64 bit and I'm having trouble to understand why.

Trying to create the smallest possible test case I ended up with
following script, which I named dodo.py and which i made executable with
chmod +x ./dodo.py

#!/usr/bin/env python
from PyQt4.QtGui import
QDialog,QGridLayout,QLabel,QComboBox,QPushButton,QApplication
a = "one"
b = "unused"
c = "also unused"
d= "ans also unused"
e = "another var"
f = "something"
class MyForm(QDialog):
def __init__(self,parent=None,config=None,ini_info=None):
super(MyForm,self).__init__(parent=parent)
grid = QGridLayout()
quit_btn = QPushButton("Quit")
quit_btn.clicked.connect(self.quit)
grid.addWidget(quit_btn,0,0)
name = "a_name"
vals_box = QComboBox()
vals_box.addItem("one")
vals_box.addItem("two")
grid.addWidget(vals_box,0,1)
self.setLayout(grid)
def quit(self):
self.close()
if __name__ == "__main__":
app = QApplication([])
myform = MyForm()
myform.show()
retcode = app.exec_()
print "last"



In order to perform the test several times I typed on the command line:

a="" ; while [ "$a" = "" ] ; do ./dodo.py ; read -t 1 a ; done

As soon as the window shows up
I click twice (slowly ) on 'one' and then on quit.

Sample output can be seen here:
gelon...@mypc:/my/directory$ a="" ; while [ "$a" = "" ] ; do ./dodo.py ;
read -t 1 a ; done
last
last
Segmentation fault
last
last
Segmentation fault
last
Segmentation fault
last
Segmentation fault
last
last
last
last
last
Segmentation fault
last
last
Segmentation fault
last
Segmentation fault


as you see the segfault happens rather often.

Does anybody see something suspicious with my code?
Can anybody else reproduce this?
as soon as I remove more lines the error seems to disappear.

What else could I do to debug this issue?

thanks for help or other ideas



If I run my script with strace ./dodo.py
I get following last lines for a run without error
> rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f65d6b3b8f0}, {0x4d9820, 
> [], SA_RESTORER, 0x7f65d6b3b8f0}, 8) = 0
> munmap(0x7f65c6344000, 622280)  = 0
> brk(0x2d71000)  = 0x2d71000
> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, 
> revents=POLLIN|POLLOUT}])
> read(7, 
> "\22\0\233\6\2\0\300\5\2\0\300\5\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 
> 4096) = 384
> writev(7, 
> [{"\232\7\2\0\210\0\300\0056\0\2\0\207\0\300\5<\0\2\0\211\0\300\5\232\7\2\0s\0\300\5"...,
>  540}, {NULL, 0}, {"", 0}], 3) = 540
> poll([{fd=7, events=POLLIN}], 1, -1)= 1 ([{fd=7, revents=POLLIN}])
> read(7, 
> "\34\0\241\6r\0\300\5\234\1\0\0\377\261\220\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"...,
>  4096) = 1472
> read(7, 0x29fa704, 4096)= -1 EAGAIN (Resource temporarily 
> unavailable)
> poll([{fd=7, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=7, revents=POLLOUT}])
> writev(7, [{"O\7\2\0\1\0\300\5<\0\2\0\0\0\300\5+\0\1\0", 20}, {NULL, 0}, {"", 
> 0}], 3) = 20
> poll([{fd=7, events=POLLIN}], 1, -1)= 1 ([{fd=7, revents=POLLIN}])
> read(7, 
> "\1\2\333\6\0\0\0\0\5\0\300\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", 4096) 
> = 32
> read(7, 0x29fa704, 4096)= -1 EAGAIN (Resource temporarily 
> unavailable)
> close(7)= 0
> write(19, "\1\v\3\200\1\0\0\0\0\0\0\0\t\0\0\0", 16) = 16
> close(19)   = 0
> open("/proc/stat", O_RDONLY|O_CLOEXEC)  = 7
> read(7, "cpu  59482 54 13580 7506040 4761"..., 8192) = 2439
> close(7)= 0
> writev(15, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12
> close(15)   = 0
> writev(13, [{"GIOP\1\2\1\5\0\0\0\0", 12}], 1) = 12
> close(13)   = 0
> close(12)   = 0
> close(11)   = 0
> unlink("/tmp/orbit-klausf/linc-1282-0-6094bc6991603") = 0
> close(14)   = 0
> write(6, "@", 1)= 1
> close(6)= 0
> close(5)= 0
> rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_NOCLDSTOP, 
> 0x7f65d6b3b8f0}, {0x7f65d40a3860, [], SA_RESTORER|SA_NOCLDSTOP, 
> 0x7f65d6b3b8f0}, 8) = 0
> exit_group(0)   


and following when an error occurs:
> writev(16, 
> [{"<\10\2\0;\6\340\5F\6\5\0!\6\340\5\10\0\340\5\0\0\0\0U\0\33\0\232\7\2\0"...,
>  16380}, {NULL, 0}, {"", 0}], 3) = 16380
> read(16, 0xbc49d4, 4096)= -1 EAGAIN (Resource temporarily 
> unavailable)
> poll([{fd=16, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=16, revents=POLLOUT}])
> writev(16, 
> [{"\232\10\t\0\3\6\340\5R\6\340\5C\6\340\5=\6\340\5\0\0\0\0\0\0\0\0\2\0\2\0"...,
>  4256}, {NULL, 0}, {"", 0}], 

Re: GUI automation tool (windows)

2010-08-11 Thread Alex Barna
I'm afraid that my first post has not been understood correctly and
most of the following posts are OT, as Ben Finney indicated.

The GUI automation has a long history, perhaps since the first
windowing system was invented. For years I've been doing this using
several different technologies/languages. But to my surprise, this
ares is not very *cultivated* by Pythonistas. Many projects (see the
link in my first post) have lost the love of their maintainers and
have not been updated for years.

Except one, pywinauto, which has a recent release in April. However,
the community activity (mailing list) is very low, website and
documentation have not been updated for long also. All this freaks me
out on adopting a technology like this :

- is there still anyone using it ?
- what if I encounter a problem but no body replies me in the mailing
list ?

Comparing with the rival AutoIt, using a BASIC-like language, which I
don't like at all, has hundreads of post in the users' forum everyday.

It makes me doubt: is Python the correct language to do GUI
automation ?



P.S.: hopefully it has been clarified, my original intention of the
post is not to debate/discuss:
- *why* automating GUI ?
- whether GUI/CLI is better.
- the points GUI or CLI is designed for.
Obvious they are all OT.


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


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread Cameron Simpson
On 11Aug2010 12:35, Tim Harig  wrote:
| > The buffering is a performance choice. Every write requires a context
| > switch from userspace to kernel space, and availability of data in the
| > pipe will wake up a downstream process blocked trying to read.
| > It is far more efficient to do as few such copies as possible, [...]
| 
| Right, I don't question the optimization.  I question whether the
| intelligence that performes that optimation should be placed within cat or
| whether it should be placed within the shell.  It seems to me that the
| shell has a better idea of how the command is being used and can therefore
| make a better decision about whether or not buffering is appropriate.

I would argue it's not much better placed, though it would be nice if
the control could be issued from there. But it can't.

Regarding the former, in this pipeline:

  cat some files... | python filter program | something else

how shall the shell know if the python filter (to take the OP's case)
wants its input line buffered (rare) or block buffered (usually ok)?

What might be useful would be a way to attach an attribute to a pipe
or other file descriptor indicating the desired buffering behaviour
that writers to the file descriptor should adopt.

Of course, the ugly sides to that are how many buffering regimes should
it be possible to express and how and when should the upstream (writing)
program decide to check? In a pipeline the pipes are made _before_ any
of the programs commence because the programs need to be attached to the
pipes (this is done before the programs themselves are dispatched). So,
_after_ dispatch the python-wanting-line-buffering issues an ioctl on
the pipe saying "I want line buffering". However, the upstream program
may well already have commenced operation before that happens. It may
even have run to completion before that happens! So, shall all upstream
programs be required to poll? How often? On every write? Shall they
receive a signal? What if they don't catch it? If the downstream
program _requires_ line buffering then the whole situation is racey
and unreliable.

You can see that on reflection this isn't easy to resolve cleanly from
_outside_ the writing program.

To do it from inside requires all programs to sprout an option like
GNU cat's -u option.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

What progress we are making. In the Middle Ages they would have burned
me. Now they are content with burning my books. - Sigmund Freud
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-11 Thread Paul Rubin
EW  writes:
> Well I can't really explain it but 1 Queue per task for what I'm
> designing just doesn't feel right to me.  It feels like it will lack
> future flexibility.

That makes no sense at all.  Multiple readers and writers per queue are
the way Python queues are designed to work.  The normal way to spray a
bunch of concurrent tasks to worker threads is just have a bunch of
workers listening to one queue.  It's the same way at the producer end.
-- 
http://mail.python.org/mailman/listinfo/python-list


cx_Oracle 5.0.4 + Python 3.1.2 + Oracle Instant Client 10.2.04; DLL Load failed on import (Win/NT)

2010-08-11 Thread tormod
Hi,

I've tried countless times to build & install cx_Oracle on Python
3.1.2, and failed every time, so I'd like to ask someone for help.
I've included step-by-step (literally) description of my last try,
with so much detail I could, to help clarify things.

I can build without errors. I can install without errors. I fail to
import.

I'm using an NT box (os:Win7)

Downloaded Oracle Instant Client 10.2.0.4
instantclient-basic-win32-10.2.0.4.zip --> extracted to C:\TEMP
\ORAIC10\bin
instantclient-sdk-win32-10.2.0.4.zip --> extracted to C:\TEMP
\ORAIC10\sdk

Downloaded source code(cx_Oracle-5.0.4.tar.gz) from 
http://cx-oracle.sourceforge.net/
--> extracted to C:\TEMP\Python\cx_Oracle

Installed Python 3.1.2 --> C:\Python31
Installed MinGW 5.1.6 --> C:\MinGW


Startet command prompt:
cd C:\TEMP\Python\cx_Oracle
PATH=%PATH%;C:\Python31;C:\MinGW\bin;C:\TEMP\ORAIC10\bin
SET ORACLE_HOME=C:\TEMP\ORAIC10
SET LD_LIBRARY_PATH=C:\TEMP\ORAIC10\sdk\lib
python setup.py build -c mingw32
python setup.py install

start python:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle
Traceback (most recent call last):
  File "", line 1, in 
ImportError: DLL load failed: The specified module could not be found.



running build
running build_ext
building 'cx_Oracle' extension
creating build
creating build\temp.win32-3.1-10g
creating build\temp.win32-3.1-10g\Release
C:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\TEMP\ORAIC10\sdk
\include -I
C:\Python31\include -IC:\Python31\PC -c cx_Oracle.c -o build
\temp.win32-3.1-10g\
Release\cx_oracle.o -DBUILD_VERSION=5.0.4 -DWITH_UNICODE
writing build\temp.win32-3.1-10g\Release\cx_Oracle.def
creating build\lib.win32-3.1-10g
C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-3.1-10g
\Release\cx_
oracle.o build\temp.win32-3.1-10g\Release\cx_Oracle.def -LC:\TEMP
\ORAIC10\bin -L
C:\TEMP\ORAIC10 -LC:\TEMP\ORAIC10\oci\lib\msvc -LC:\TEMP\ORAIC10\sdk
\lib\msvc -L
C:\Python31\libs -LC:\Python31\PCbuild -loci -lpython31 -lmsvcr90 -o
build\lib.w
in32-3.1-10g\cx_Oracle.pyd




running install
running build
running build_ext
running install_lib
copying build\lib.win32-3.1-10g\cx_Oracle.pyd -> C:\Python31\Lib\site-
packages
running install_data
running install_egg_info
Removing C:\Python31\Lib\site-packages\cx_Oracle-5.0.4-py3.1.egg-info
Writing C:\Python31\Lib\site-packages\cx_Oracle-5.0.4-py3.1.egg-info


I've opened the cx_Oracle.pyd with Dependency Walker (http://
www.dependencywalker.com/) and DW reports it can't find: OCI.DLL,
PYTHON31.DLL, MSVCR90.DLL (why?)

Appreciate any help, even wildshots and 2 cents are welcome - I'll try
everything.

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


Re: urgent requirement at Hyderabad

2010-08-11 Thread Emile van Sebille

On 8/11/2010 12:39 PM MRAB said...

Stefan Behnel wrote:

In case anyone wondered: Hyderabad is likely referring to some place
in Asia:

http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29


And Berlin is likely some place in Europe:

http://en.wikipedia.org/wiki/Berlin_(disambiguation)

:-)


And Paris is likely someplace in the US...

http://en.wikipedia.org/wiki/Paris_%28disambiguation%29

Emile :))


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


Re: looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-11 Thread Thomas Jollans
On Wednesday 11 August 2010, it occurred to Baba to exclaim:
> level: beginner
> 
> exercise: given that packs of McNuggets can only be bought in 6, 9 or
> 20 packs, write an exhaustive search to find the largest number of
> McNuggets that cannot be bought in exact quantity.

The MacDonald's at Nuremberg central station once sold me 25 in a 20-pack. So 
this won't work.

> 
> exercise source:
> http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00
> -introduction-to-computer-science-and-programming-fall-2008/assignments/pse
> t2.pdf
> 
> please help me write this code
> 
> i believe it's something along the lines of this:
> 
> c=0
> sol=[]
> for n in range (0,10):
>  for a in range (0,10):
>   for b in range (0,10):
>for c in range (0,10):
> sol=6*a+9*b+20*c
> if sol!=n:
>  c+=1
> if c==6:
>  print sol
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python interview quuestions

2010-08-11 Thread Peter
On Aug 11, 8:50 pm, Tim Chase  wrote:
> On 08/11/10 01:24, Terry Reedy wrote:
>
> > On 8/10/2010 8:08 PM, Roy Smith wrote:
> >> In any case, if the candidate were to submit somebody else's
> >> work, it would come out pretty quickly as we discussed their
> >> code.  I suppose one question I might ask would be, "Can you
> >> explain why, when I copy-paste one of your comments into a
> >> google search box, your entire program appears?"
>
> > Mostly likely because I wrote the original...
>
> > would be my answer.
>
> Unfortunately there are candidates who would give your answer but
> then have trouble with "Then why are the Last-Modified HTTP
> headers showing a date several months before our interview?"
> It's as bad as the phone-interviews I've done where in the
> background I can hear the person on the other end typing my
> questions into a search box and reading off answers.  On the
> bright side, those are short interviews... ;-)
>
> -tkc

I know we are straying somewhat here :-) But as an interviewer way
back when in the never-never, I used to look at the interviewee's work
history i.e. 18 months here, 12 months there, 6 months here etc and
pretty much wipe them from my short-list based on that alone :-)
Because it takes at least 3 months for a programmer to get "up to
speed" fitting into your company and on your applications, they are
usually only really productive and really "hitting their stride" at 6
months - somebody who "job hops" will already be looking for the next
job by that time!

I really did't have time to waste on these people - then there was the
agents fee for finding them for you - big investment for zero return.

So I would recommend to anybody that they attempt to maintain a stable
work history in this respect. For example, my personal work history is
8, 7.5, 8.5, 0.5, 3, 3, 8 (years that is). My current company is
extremely stable, I enjoy the work, so I don't see any reason why I
won't be here until I retire (or die at my desk - whichever comes
first :-)).

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


Re: How to input values of the matrix from keyboard in python

2010-08-11 Thread Chris Rebert
On Wed, Aug 11, 2010 at 12:06 PM, Chris Rebert  wrote:
> On Wed, Aug 11, 2010 at 11:43 AM, Pramod  wrote:
>> Hi
>>
>>   I want to know the how we input values into the matrix (N*N size)
>> from keyboard in python,
>>
>> Here I wrote Matrix programe in C++
>>
>> This  asks values from key board and print on the console N*N matrix ;
>>
>> Thanks in advance 
>>
>>
>> #include
>> using namespace std;
>> int main()
>> {
>>        double **a;
>>        int i,j,n;
>>        cout<<"Enter size of the matrix\n";
>>        cin>>n;
>>                for(i=0;i>                for(j=0;j>                        a[i][j] = random();
>> //or
>>                //cin>>a[i][j];
>>                cout<>        }
>>        for(i=0;i>                for(j=0;j>                        cout<>                cout<>        }
>>        delete [] a;
>> }
>
> from random import random
> from sys import exit
>
> while True:
>    try:
>        N = int(raw_input("Enter size of the matrix: "))
>    except ValueError:
>        print "Invalid input. Try again."
>    except EOFError:
>        exit(1)
>    else:
>        break
>
> a = [[random() for j in xrange(N)] for i in xrange(N)]
> stringified = "\n".join("\t".join(row) for row in a)
> print stringified

Should have prefaced that with an "untested" disclaimer.
Make that:
stringified = "\n".join("\t".join(str(cell) for cell in row) for row in a)

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


Re: mi

2010-08-11 Thread Chris Rebert
On Wed, Aug 11, 2010 at 12:45 PM, Eric J. Van der Velden
 wrote:
> Hello,
>
> I have these types,
>
> class A:
>        def __init__(s):
>                super().__init__()
>                print("A")
> class B(A):
>        def __init__(s):
>                super().__init__()
>                print("B")
> class C(A):
>        def __init__(s):
>                super().__init__()
>                print("C")
> class D(B,C):
>        def __init__(s):
>                super().__init__()
>                print("D")
>
> If I do (in 3.1)
 d=D()
> A
> C
> B
> D
>
> Why this order?

Well, it's clearer for illustration purposes if you do the print()s
"preorder" (before the super calls) rather than "postorder", but
anyway...

Because that's how Python's Method Resolution Order (MRO) works. Very
smart people have thought a lot about this. It is The Right Order
(tm).
To understand *why* it's right, read:
http://www.python.org/download/releases/2.2.3/descrintro/#mro
and (if you dare):
http://www.python.org/download/releases/2.3/mro/

The order (of the method calls, not the print()s) is (extremely
roughly) from most derived to most ancestral, without calling anything
twice. Is that not a logical and sensible (albeit not necessarily
obvious) rule?

> I thought, first to D, then B, then A. He prints "A".
> He comes back in B and prints "B". He goes to C. Then somehow he
> doesn't go again to A. He prints "C". Then back to D and prints "D".

"super()" is a bit of a misnomer. **It doesn't necessarily call a
superclass method.** In fact, the Dylan programming language (which
Python borrowed its MRO from) instead names the analogous function
"next-method" because it calls the method that comes after the current
one in the MRO.

Here's what actually happened: D called B. Then B called *C* (seems
bizarre, yes). C is obviously not a superclass of B; but this is the
only way to make things work out right (see aforelinked docs). From
there, C called A, and the rest is obvious.

Multiple inheritance can get tricky; avoid it when possible.

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


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread RG
In article ,
 RG  wrote:

> In article ,
>  Tim Harig  wrote:
> 
> > On 2010-08-11, RG  wrote:
> > > In article ,
> > >  Tim Harig  wrote:
> > >
> > >> On 2010-08-11, RG  wrote:
> > >> > I'm writing a system in a different language but want to use a Python 
> > >> > library.  I know of lots of ways to do this (embed a Python 
> > >> > interpreter, 
> > >> > fire up a python server) but by far the easiest to implement is to 
> > >> > have 
> > >> > the main program spawn a Python interpreter and interact with it 
> > >> > through 
> > >> > its stdin/stdout.
> > >> 
> > >> Or, open python using a socket.
> > >
> > > You mean a TCP/IP socket?  Or a unix domain socket?  The former has 
> > > security issues, and the latter seems like a lot of work.  Or is there 
> > > an easy way to do it that I don't know about?
> > 
> > I was referring to unix domain sockets or more specifically stream
> > pipes. I guess it depends what language you are using and what libraries
> > you have access to.  Under C, working with stream pipes is no more trivial
> > then using pipe().  You can simply create the socket descriptors using
> > socketpair().  Keep one of the descriptors for your process and pass the
> > other to the python child process as both stdin and stdout.
> 
> Ah.  That is in fact exactly what I am doing, and that is how I first 
> encountered this problem.
> 
> rg

And now I have encountered another problem:

-> print sys.stdin.encoding
<- None

But when I run from a terminal:

[...@mickey:~]$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'UTF-8'


I thought the value of sys.stdin.encoding was hard-coded into the Python 
executable at compile time, but that's obviously wrong.  So how does 
Python get the value of sys.stdin.encoding?

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


Re: most popular gui framework for python

2010-08-11 Thread Peter
On Aug 12, 6:13 am, Thomas Jollans  wrote:
> On Wednesday 11 August 2010, it occurred to Back9 to exclaim:
>
> > Hi,
>
> > Does anyone know of what is the most popular gui framework for python
> > application?
>
> I'd guess at Tkinter - it's part of the standard library.
> Another quite popular option is PyGtk. Other good ones include wxPython, PyQt,
> and PySide.

Lots of choices - you could try Jython as well, then you have access
to all the Java GUI framework :-)

Personally, I have used Tkinter, PMW (Widgets built on Tkinter) - all
of my GUI stuff to date is written using these.

I have tried WxPython - I found it quite difficult to learn, but this
was quite some years ago now and perhaps there are some easy books
that will help you ease into it.

I am currently experimenting with PyQt - I have Mark Summerfield's
book, "Rapid GUI Programming with Python and Qt" - very readable book.
Now that the Qt license is more friendly to the "hobbyist" I think I
will switch all of my GUI work over to PyQt.

There are so many these days (just look at the Python wiki page on
GUIs) that you can't really try them all - just not enough hours in
the day. I would suggest you have a quick browse of what's available
and then select one or two to focus on. Most are pretty well
"portable" between multiple platforms - but realistically I have never
used anything other than a Windoze platform cross-platform
compatibility may not be such a big deal.

I would strongly recommend reading the Python Wiki page on GUI
programming: http://wiki.python.org/moin/GuiProgramming


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


Re: looping through possible combinations of McNuggets packs of 6,9 and 20

2010-08-11 Thread News123

As said in the instructions.

if you find six consecutive numbers, that can be bough in exact
quantity, then you know, that all bigger numbers can also be bought in
exact quantity.


I would do a brute force approach


first I would create one function, which will try to find out, whether
one can buy an exact quantity of n nuggets.


example function prototype


def can_buy(n_nuggets):
# here you have to write your code


the function should return True or if you're curious a list of packages
and quantities if quantity n_nuggets can be bought

otherwise it should return False or an empty list.



then you can create another function which will start with 6 nuggets (or
if you like to with 1 nugget)
and which will count how many times in sequence it managed to return a
result. (by using the function can_buy() and managibng a counter)

If it found 6 results in sequence, then you know, that all bigger
numbers can also be bought and that the biggest number, which could not
be bought was 6 numbers before.

I think nobody here will write the soultion for you.

If you write some more code and if you tell us what it's supposed to to
and with what exectly you're having trouble with I can give you more hints.




On 08/11/2010 10:14 PM, Baba wrote:
> level: beginner
> 
> exercise: given that packs of McNuggets can only be bought in 6, 9 or
> 20 packs, write an exhaustive search to find the largest number of
> McNuggets that cannot be bought in exact quantity.
> 
> exercise source:
> http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf
> 
> please help me write this code
> 
> i believe it's something along the lines of this:
> 
> c=0
> sol=[]
> for n in range (0,10):
>  for a in range (0,10):
>   for b in range (0,10):
>for c in range (0,10):
> sol=6*a+9*b+20*c
> if sol!=n:
>  c+=1
> if c==6:
>  print sol


Not very modular.
> c=0 # c could have a meaningful name and probably a different  one
> # it seems, that you reuse c also in a for statement
> sol=[]
> for n in range (0,10): # n should not only go from 0 to 10
>   #  but from 0 until c is 6

# i'd put this in a separate function it makes it also easier for
# you to understand and test
>  for a in range (0,10):
>   for b in range (0,10):
>for c in range (0,10): # c used here and lso as counter
> sol=6*a+9*b+20*c
> if sol!=n:
>  c+=1
> if c==6:
>  print "solution is",sol-6
> 


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


Re: Queue cleanup

2010-08-11 Thread EW
On Aug 11, 2:52 pm, Paul Rubin  wrote:
> EW  writes:
> > Well I cared because I thought garbage collection would only happen
> > when the script ended - the entire script.  Since I plan on running
> > this as a service it'll run for months at a time without ending.  So I
> > thought I was going to have heaps of Queues hanging out in memory,
> > unreferenced and unloved.  It seemed like bad practice so I wanted to
> > get out ahead of it.
>
> Even if GC worked that way it wouldn't matter, if you use just one queue
> per type of task.  That number should be a small constant so the memory
> consumption is small.

Well I can't really explain it but 1 Queue per task for what I'm
designing just doesn't feel right to me.  It feels like it will lack
future flexibility.  I like having 1 Queue per producer thread object
and the person instantiating that object can do whatever he wants with
that Queue.  I can't prove I'll need that level of flexibility but I
don't see why it' bad to have.  It's still a small number of Queues,
it's just a small, variable, number of Queues.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mi

2010-08-11 Thread Thomas Jollans
On Wednesday 11 August 2010, it occurred to Eric J. Van der Velden to exclaim:
> Hello,
> 
> I have these types,
> 
> class A:
> def __init__(s):
> super().__init__()
> print("A")
> class B(A):
> def __init__(s):
> super().__init__()
> print("B")
> class C(A):
> def __init__(s):
> super().__init__()
> print("C")
> class D(B,C):
> def __init__(s):
> super().__init__()
> print("D")
> 
> If I do (in 3.1)
> 
> >>> d=D()
> 
> A
> C
> B
> D
> 
> Why this order? I thought, first to D, then B, then A. He prints "A".
> He comes back in B and prints "B". He goes to C. Then somehow he
> doesn't go again to A. He prints "C". Then back to D and prints "D".

Think again about what you're seeing here. You're printing AFTER the call to 
super().__init__(). That means that it first walks the inheritance hierarchy, 
and then prints -- your trace is "the wrong way around"

So, what happens is: you call D(). In it, super() delegates to B(). Which has 
super delegate to C(), which then has super() delegate finally to A().

D, B, C, A

You say you were expecting D, B, A -- but what of C? You also imply that you 
would have expected two visits to A -- but that would defeat the point of 
super() -- you don't actually want one constructor to be called twice: the 
constructor almost certainly isn't written with that possibility in mind.

> 
> Thanks,
> 
> Eric J.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread RG
In article ,
 Tim Harig  wrote:

> On 2010-08-11, RG  wrote:
> > In article ,
> >  Tim Harig  wrote:
> >
> >> On 2010-08-11, RG  wrote:
> >> > I'm writing a system in a different language but want to use a Python 
> >> > library.  I know of lots of ways to do this (embed a Python interpreter, 
> >> > fire up a python server) but by far the easiest to implement is to have 
> >> > the main program spawn a Python interpreter and interact with it through 
> >> > its stdin/stdout.
> >> 
> >> Or, open python using a socket.
> >
> > You mean a TCP/IP socket?  Or a unix domain socket?  The former has 
> > security issues, and the latter seems like a lot of work.  Or is there 
> > an easy way to do it that I don't know about?
> 
> I was referring to unix domain sockets or more specifically stream
> pipes. I guess it depends what language you are using and what libraries
> you have access to.  Under C, working with stream pipes is no more trivial
> then using pipe().  You can simply create the socket descriptors using
> socketpair().  Keep one of the descriptors for your process and pass the
> other to the python child process as both stdin and stdout.

Ah.  That is in fact exactly what I am doing, and that is how I first 
encountered this problem.

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


Re: most popular gui framework for python

2010-08-11 Thread Thomas Jollans
On Wednesday 11 August 2010, it occurred to Back9 to exclaim:
> Hi,
> 
> Does anyone know of what is the most popular gui framework for python
> application?

I'd guess at Tkinter - it's part of the standard library.
Another quite popular option is PyGtk. Other good ones include wxPython, PyQt, 
and PySide.
-- 
http://mail.python.org/mailman/listinfo/python-list


looping through possible combinations of McNuggets packs of 6, 9 and 20

2010-08-11 Thread Baba
level: beginner

exercise: given that packs of McNuggets can only be bought in 6, 9 or
20 packs, write an exhaustive search to find the largest number of
McNuggets that cannot be bought in exact quantity.

exercise source:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf

please help me write this code

i believe it's something along the lines of this:

c=0
sol=[]
for n in range (0,10):
 for a in range (0,10):
  for b in range (0,10):
   for c in range (0,10):
sol=6*a+9*b+20*c
if sol!=n:
 c+=1
if c==6:
 print sol


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


Re: python interview quuestions

2010-08-11 Thread Paul Rubin
geremy condra  writes:
> I can't recall who it was, but I remember being very impressed by a
> company that did a variant of this a few years ago: they put
> programming problems on the sides of pay phones, taxis, etc. with a
> note that said 'If you can solve this, call us'. I have zero doubt
> that they got some top talent that way.

Several companies have done that.  You might be thinking of ITA
Software:

http://www.itasoftware.com/careers/puzzle_archive.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python interview quuestions

2010-08-11 Thread geremy condra
On Wed, Aug 11, 2010 at 6:04 AM, Roy Smith  wrote:
> In article <4c6298c1$0$11101$c3e8...@news.astraweb.com>,
>  Steven D'Aprano  wrote:
>
>> Sounds ridiculous, but apparently there are vast hordes of people who can
>> barely program "Hello World" applying for programming jobs. One figure
>> bandied about -- how accurately, I don't know -- is 199 out of every 200
>> job applicants for programming jobs are barely capable of writing a line
>> of code.
>
> By the same token, there are lots of people with advanced degrees in
> computer science who can't code their way out of a paper bag.
>
> One advantage of the take-home test is that you can prepare the test
> once and amortize the preparation cost over many applicants.  It's a big
> investment of time to interview somebody.  By the time I get up to
> investing an hour or so of my time on a phone screen, I'd like to weed
> out the obvious rejects as cheaply as possible.
>
> Even more interesting is to publish some problems on your web site and
> instruct applicants to submit a solution to one of them along with their
> resume.  This makes the per-applicant cost to administer the exam
> essentially zero.  It also has the nice side-effect of weeding out the
> resume spammers.  To be honest, I've never done this, but I've seen
> companies that do.  I may try it sometime.

I can't recall who it was, but I remember being very impressed by a
company that did a variant of this a few years ago: they put
programming problems on the sides of pay phones, taxis, etc. with a
note that said 'If you can solve this, call us'. I have zero doubt
that they got some top talent that way.

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


Re: most popular gui framework for python

2010-08-11 Thread J.O. Aho
Back9 wrote:

> Does anyone know of what is the most popular gui framework for python
> application?

Don't think it's the most popular, but I think it may be the one which works
for quite a lot of different platforms, PyQt, works fine on my desktop as
cellphone.

-- 

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


mi

2010-08-11 Thread Eric J. Van der Velden
Hello,

I have these types,

class A:
def __init__(s):
super().__init__()
print("A")
class B(A):
def __init__(s):
super().__init__()
print("B")
class C(A):
def __init__(s):
super().__init__()
print("C")
class D(B,C):
def __init__(s):
super().__init__()
print("D")

If I do (in 3.1)
>>> d=D()
A
C
B
D

Why this order? I thought, first to D, then B, then A. He prints "A".
He comes back in B and prints "B". He goes to C. Then somehow he
doesn't go again to A. He prints "C". Then back to D and prints "D".

Thanks,

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


Re: Is there a Python equivalent to Perl's File::Listing::parse_dir

2010-08-11 Thread Thomas Jollans
On Wednesday 11 August 2010, it occurred to John Nagle to exclaim:
> This is especially useful for FTP sites.

It sounds like you're trying to use HTTP to something a lot more easily done 
with FTP, without any reason not to use FTP.

http://docs.python.org/library/ftplib.html#ftplib.FTP.dir
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread Tim Harig
On 2010-08-11, RG  wrote:
> In article ,
>  Tim Harig  wrote:
>
>> On 2010-08-11, RG  wrote:
>> > I'm writing a system in a different language but want to use a Python 
>> > library.  I know of lots of ways to do this (embed a Python interpreter, 
>> > fire up a python server) but by far the easiest to implement is to have 
>> > the main program spawn a Python interpreter and interact with it through 
>> > its stdin/stdout.
>> 
>> Or, open python using a socket.
>
> You mean a TCP/IP socket?  Or a unix domain socket?  The former has 
> security issues, and the latter seems like a lot of work.  Or is there 
> an easy way to do it that I don't know about?

I was referring to unix domain sockets or more specifically stream
pipes. I guess it depends what language you are using and what libraries
you have access to.  Under C, working with stream pipes is no more trivial
then using pipe().  You can simply create the socket descriptors using
socketpair().  Keep one of the descriptors for your process and pass the
other to the python child process as both stdin and stdout.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GUI automation tool (windows)

2010-08-11 Thread CM
On Aug 9, 8:10 am, Alex Barna  wrote:
> I know that this question has been asked for several times, but it
> surprises that there is no tool under very active development and the
> community activities are very low (mailing list posts).
>
> All the tools listed in:
>
> http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#GUITestingTools
>
> Comparing with AutoIt (www.autoitscript.com), it has tens to hundreds
> of posts everyday. AutoIt uses a proprietary BASIC -like language, and
> to be honest, I don't like it and I prefer a Pythonic solution.
>
> pywinauto seems to be the best choice but the community has been very
> low also. The same happens in pyguiunit, pyAA, WATSUP, all development
> seem to be ceased.
>
> So what happens to this field (Windows GUI automation) ?

This is a little late, but you might want to check out Sikuli.  Search
for it in
this forum, there is a long thread about it.  It might be a new useful
way to
write GUI tests.  I have no real idea, though.

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


Re: Confused: Newbie Function Calls

2010-08-11 Thread Pinku Surana
On Aug 11, 12:39 pm, fuglyducky  wrote:
> On Aug 11, 9:31 am, Pinku Surana  wrote:
>
>
>
>
>
> > On Aug 11, 12:07 pm, fuglyducky  wrote:
>
> > > I am a complete newbie to Python (and programming in general) and I
> > > have no idea what I'm missing. Below is a script that I am trying to
> > > work with and I cannot get it to work. When I call the final print
> > > function, nothing prints. However, if I print within the individual
> > > functions, I get the appropriate printout.
>
> > > Am I missing something??? Thanks in advance
>
> > > 
> > > # Global variable
> > > sample_string = ""
>
> > > def gen_header(sample_string):
> > >     HEADER = """
> > >     mymultilinestringhere
> > >     """
>
> > >     sample_string += HEADER
> > >     return sample_string
>
> > > def gen_nia(sample_string):
> > >     NIA = """
> > >     anothermultilinestringhere
> > >     """
>
> > >     sample_string += NIA
> > >     return sample_string
>
> > > gen_header(sample_string)
> > > gen_nia(sample_string)
>
> > > print(sample_string)
>
> > There are 2 problems with your program.
>
> > (1) If you want to use a global variable in a function, you have to
> > add the line "global sample_string" to the beginning of that
> > function.
>
> > (2) Once you do (1), you will get an error because you've got
> > sample_string as a global and a function parameter. Which one do you
> > want to use in the function? You should change the name of the
> > parameter to "sample" to solve that confusion.
>
> > Here's the result, which works for me:
>
> > sample_string = ""
> > def gen_header(sample):
> >     global sample_string
> >     HEADER = """
> >     mymultilinestringhere
> >     """
> >     sample_string = sample + HEADER
> >     return sample_string
> > def gen_nia(sample):
> >     global sample_string
> >     NIA = """
> >     anothermultilinestringhere
> >     """
> >     sample_string = sample + NIA
> >     return sample_string
> > gen_header(sample_string)
> > gen_nia(sample_string)
> > print(sample_string)
>
> Thanks! That did the trick.
>
> I am a bit confused though. I tried to follow a sample in a book
> (which works) where I didn't have to 1) pass the global variable as a
> parameter into the function, 2) did not have to define the global
> variable within the function. I apologize if this is a super stupid
> question but if it is global, why do I have to pass it into the
> function? Shouldn't the global variable be accessible from anywhere???

Since you're new to programming, it's important to understand the
fundamentals.

x = 0 # GLOBAL

def fun(x): # PARAMETER, a type of LOCAL variable
y = 1   # LOCAL
x += y  # Which x do you mean? The local or global?
print x # What is this value?

fun(x)
print x # What is this value?


Even though I used the same name "x" for a local and global variable,
they are actually completely different. When I call "fun(x)" it COPIES
the global value of "x" into the local variable "x" in "fun". In this
code, Python assumes in "x += y" you want to use the LOCAL variable.
To Python the code looks like this:

x_global = 0

def fun(x_local):
y_local = 1
x_local += y_local
print x_local

fun(x_global)
print x_global   # This is never changed!

If that's not what you want, then you have to explicitly tell Python
that you want to use the global value (this is not good programming
style, by the way!). That's what the "global" keyword does.

Try to write some small programs that pass around numbers and strings
with different variable names. Try every combination you can think of
until you get good at predicting what the output is.

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


Re: urgent requirement at Hyderabad

2010-08-11 Thread MRAB

Stefan Behnel wrote:
In case anyone wondered: Hyderabad is likely referring to some place in 
Asia:


http://en.wikipedia.org/wiki/Hyderabad_%28disambiguation%29


And Berlin is likely some place in Europe:

http://en.wikipedia.org/wiki/Berlin_(disambiguation)

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


most popular gui framework for python

2010-08-11 Thread Back9
Hi,

Does anyone know of what is the most popular gui framework for python
application?

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


Re: Queue cleanup

2010-08-11 Thread MRAB

Paul Rubin wrote:

EW  writes:

Well I cared because I thought garbage collection would only happen
when the script ended - the entire script.  Since I plan on running
this as a service it'll run for months at a time without ending.  So I
thought I was going to have heaps of Queues hanging out in memory,
unreferenced and unloved.  It seemed like bad practice so I wanted to
get out ahead of it.


Even if GC worked that way it wouldn't matter, if you use just one queue
per type of task.  That number should be a small constant so the memory
consumption is small.


That's basically how _non_-garbage-collected languages work! :-)
--
http://mail.python.org/mailman/listinfo/python-list


How to give matrix input from keyboard or file in python

2010-08-11 Thread Pramod





I want to write the following programm in python .


Main objective is input from keyoard to enter elements into the
matrix .


Thanks in advance



#include
#include
#include
using namespace std;
int main()
{
double **a;
int i,j,n;
cout<<"Enter size of the matrix\n";
cin>>n;
a=new double* [n];
for(i=0;i>a[i][j];
cout<
stringified = "\n".join("\t".join(row) for row in a)
  File "two.py", line 16, in 
stringified = "\n".join("\t".join(row) for row in a)
TypeError: sequence item 0: expected string, float found

Thanks in Advance




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


Re: Microsoft lessening commitment to IronPython and IronRuby

2010-08-11 Thread Jason Earl
On Tue, Aug 10 2010, Ben Finney wrote:

> Steven D'Aprano  writes:
>
>> On Tue, 10 Aug 2010 20:07:06 +1200, Gregory Ewing wrote:
>> > Is there any way for a non-.NET program to access a .NET library? Or
>> > is it necessary to drink the entire bottle of .NET kool-aid?
>>
>> http://www.mono-project.com/Main_Page
>
> Anyone thinking of using Mono needs to be aware of the dangers of
> software patents in general, and of .NET in paticular.
>
> The copyright license for Mono is under free software terms. But that
> gives no license at all for the patents. Novell, who have an exclusive
> deal for those patents, happily encourages use of Mono by third
> parties.
>
> The controversy has raged for a number of years. For more coverage
> than you have time for, see
> http://techrights.org/wiki/index.php/Mono>.  The issue has
> polarised discussion, unfortunately, and there is a lot of
> name-calling and hyperbole on the record now.
>
> As the Mono site hints, the patent situation for .NET is *very* muddy.
> Microsoft hold patents covering much of .NET, but have made a
> (non-binding) “Community Promise” that applies to *some* parts of .NET
> http://www.mono-project.com/Licensing#Patents>.

Which is more of a promise than Microsoft has given to Python.  I am not
arguing for Mono, as I am not a fan.  But if you honestly think that
Python doesn't infringe on some of Microsoft's patents you are crazy.
So where is the promise from Microsoft saying that they won't sue the
Python development team into oblivion, or Python end users, for that
matter?

There isn't one.

So while the Mono promise doesn't cover all of Mono, it does cover
*some* of Mono, which is better than what Python can say.  If you happen
to be believe that Microsoft is likely to attack Free Software via
patents then Mono is arguably the safest choice.  Especially if you
confine yourself to the ECMA-sponsored core and the Free Software
libraries that are not re-implementations of Microsoft's technology.

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


Re: How to input values of the matrix from keyboard in python

2010-08-11 Thread MRAB

Pramod wrote:

Hi

   I want to know the how we input values into the matrix (N*N size)
from keyboard in python,

Here I wrote Matrix programe in C++


This  asks values from key board and print on the console N*N matrix ;


[snip]

Read from the keyboard using raw_input() (in Python 2, or input() in
Python 3) and convert to float.

Incidentally, your C++ program doesn't allocate the array.

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


Re: How to input values of the matrix from keyboard in python

2010-08-11 Thread Chris Rebert
On Wed, Aug 11, 2010 at 11:43 AM, Pramod  wrote:
> Hi
>
>   I want to know the how we input values into the matrix (N*N size)
> from keyboard in python,
>
> Here I wrote Matrix programe in C++
>
> This  asks values from key board and print on the console N*N matrix ;
>
> Thanks in advance 
>
>
> #include
> using namespace std;
> int main()
> {
>        double **a;
>        int i,j,n;
>        cout<<"Enter size of the matrix\n";
>        cin>>n;
>                for(i=0;i                for(j=0;j                        a[i][j] = random();
> //or
>                //cin>>a[i][j];
>                cout<        }
>        for(i=0;i                for(j=0;j                        cout<                cout<        }
>        delete [] a;
> }

from random import random
from sys import exit

while True:
try:
N = int(raw_input("Enter size of the matrix: "))
except ValueError:
print "Invalid input. Try again."
except EOFError:
exit(1)
else:
break

a = [[random() for j in xrange(N)] for i in xrange(N)]
stringified = "\n".join("\t".join(row) for row in a)
print stringified


If you're doing serious work with matrices, look at the NumPy package.

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


Re: passing file from command line startup

2010-08-11 Thread MRAB

Bradley Hintze wrote:

Hi all,

Is there a way that I can startup my script and pass it a file? For example:

~$ python myscript.py mytext.txt

and then access mytext.txt in myscript.py?

As a long shot, for myscript.py I tried

def __init__(fle):
print fle

expecting the full path to mytext.txt to be printed but that didn't work.

Obviously I've never done this. I hope the above makes sense. any help
will be greatly appreciated.


import sys

print sys.argv
--
http://mail.python.org/mailman/listinfo/python-list


Re: passing file from command line startup

2010-08-11 Thread Robert Kern

On 8/11/10 1:47 PM, Bradley Hintze wrote:

Hi all,

Is there a way that I can startup my script and pass it a file? For example:

~$ python myscript.py mytext.txt

and then access mytext.txt in myscript.py?

As a long shot, for myscript.py I tried

def __init__(fle):
 print fle

expecting the full path to mytext.txt to be printed but that didn't work.

Obviously I've never done this. I hope the above makes sense. any help
will be greatly appreciated.


http://docs.python.org/library/sys#sys.argv

I do recommend using argparse to process command line arguments, even for the 
simplest cases:


  http://docs.python.org/library/argparse

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: passing file from command line startup

2010-08-11 Thread Peter Otten
Bradley Hintze wrote:

> Hi all,
> 
> Is there a way that I can startup my script and pass it a file? For
> example:
> 
> ~$ python myscript.py mytext.txt
> 
> and then access mytext.txt in myscript.py?
> 
> As a long shot, for myscript.py I tried
> 
> def __init__(fle):
> print fle
> 
> expecting the full path to mytext.txt to be printed but that didn't work.
> 
> Obviously I've never done this. I hope the above makes sense. any help
> will be greatly appreciated.
> 
> Thanks,

You are looking for sys.argv:

$ cat tmp.py
import sys
print sys.argv
$ python tmp.py one two 'many arguments'
['tmp.py', 'one', 'two', 'many arguments']

Around that simple mechanism fancier libraries have been built:

http://docs.python.org/library/argparse.html

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


Re: urgent requirement at Hyderabad

2010-08-11 Thread Edward A. Falk
In article ,
Stefan Behnel   wrote:
>In case anyone wondered: Hyderabad is likely referring to some place in Asia:

It's one of the high-tech cities in India.  A lot of out-sourcing
winds up there.

-- 
-Ed Falk, f...@despams.r.us.com
http://thespamdiaries.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-11 Thread Paul Rubin
EW  writes:
> Well I cared because I thought garbage collection would only happen
> when the script ended - the entire script.  Since I plan on running
> this as a service it'll run for months at a time without ending.  So I
> thought I was going to have heaps of Queues hanging out in memory,
> unreferenced and unloved.  It seemed like bad practice so I wanted to
> get out ahead of it.

Even if GC worked that way it wouldn't matter, if you use just one queue
per type of task.  That number should be a small constant so the memory
consumption is small.
-- 
http://mail.python.org/mailman/listinfo/python-list


passing file from command line startup

2010-08-11 Thread Bradley Hintze
Hi all,

Is there a way that I can startup my script and pass it a file? For example:

~$ python myscript.py mytext.txt

and then access mytext.txt in myscript.py?

As a long shot, for myscript.py I tried

def __init__(fle):
print fle

expecting the full path to mytext.txt to be printed but that didn't work.

Obviously I've never done this. I hope the above makes sense. any help
will be greatly appreciated.

Thanks,
-- 
Bradley J. Hintze
Graduate Student
Duke University
School of Medicine
801-712-8799
-- 
http://mail.python.org/mailman/listinfo/python-list


How to input values of the matrix from keyboard in python

2010-08-11 Thread Pramod
Hi

   I want to know the how we input values into the matrix (N*N size)
from keyboard in python,

Here I wrote Matrix programe in C++


This  asks values from key board and print on the console N*N matrix ;




Thanks in advance 


#include
using namespace std;
int main()
{
double **a;
int i,j,n;
cout<<"Enter size of the matrix\n";
cin>>n;
for(i=0;i>a[i][j];
cout

Re: Queue cleanup

2010-08-11 Thread EW
On Aug 11, 2:16 pm, Paul Rubin  wrote:
> EW  writes:
> > I thought about doing it that way and I could do it that way but it
> > still seems like there should be a way to clean up Queues on my own.
> > If I did it this way then I guess I'd be relying on garbage collection
> > when the script ended to clean up the Queues for me.
>
> Oh, I see.  As long as it's possible to start new producer or consumer
> threads that touch a queue, obviously that queue has to still be around.
> If the program starts all its threads at the beginning, then runs til
> they exit, then does more stuff, then you could do something like:
>
>     # make dictonary of queues, one queue per task type
>     queues = {'sql': Queue(), 'logging': Queue(), ... }
>
>     for i in 
>        threading.Thread(target=your_handler, args=[queues])
>
>     del queues
>
> and then when all the threads exit, there are no remaining references to
> the queues.  But why do you care?  Queues aren't gigantic structures,
> they're just a list (collections.deque) with an rlock.  It's fine to let
> the gc clean them up; that's the whole point of having a gc in the first
> place.

Well I cared because I thought garbage collection would only happen
when the script ended - the entire script.  Since I plan on running
this as a service it'll run for months at a time without ending.  So I
thought I was going to have heaps of Queues hanging out in memory,
unreferenced and unloved.  It seemed like bad practice so I wanted to
get out ahead of it.

But the GC doesn't work the way I thought it worked so there's really
no problem I guess. I was just confused on garbage collection it seems.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread RG
In article ,
 Tim Harig  wrote:

> On 2010-08-11, RG  wrote:
> > I'm writing a system in a different language but want to use a Python 
> > library.  I know of lots of ways to do this (embed a Python interpreter, 
> > fire up a python server) but by far the easiest to implement is to have 
> > the main program spawn a Python interpreter and interact with it through 
> > its stdin/stdout.
> 
> Or, open python using a socket.

You mean a TCP/IP socket?  Or a unix domain socket?  The former has 
security issues, and the latter seems like a lot of work.  Or is there 
an easy way to do it that I don't know about?

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


Re: How to swallow traceback message

2010-08-11 Thread Peter Otten
Back9 wrote:

> I run my py app to display a file's contents, and it is normally very
> long.
> So I use it like below:
> 
> python myapp.py input_file | more
> to see them step by step.
> 
> But when I try to exit it, normally I use Ctrl+ C key to quit it.
> Problem is every time I do like it, it shows Traceback message and it
> makes my app not professional.
> 
> How do I handle it gracefully.

Step 1, provoke the error:

$ python -c"while 1: print 42" | head -n1
42
Traceback (most recent call last):
  File "", line 1, in 
IOError: [Errno 32] Broken pipe

Step 1a, read the error message carefully ;)

Step 2, catch the error:

$ python -c"try:
while 1: print 42
except IOError as e:
if e.errno != 32: raise
" | head -n1
42

Step 3, repeat if necessary. IOError is only one example.

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


Is there a Python equivalent to Perl's File::Listing::parse_dir

2010-08-11 Thread John Nagle

  Perl has a function which will take a remote directory page, in
the form that most web sites return for a file directory, and
parse it into a useful form:

http://www.xav.com/perl/site/lib/File/Listing.html

This is especially useful for FTP sites.

Is there a Python equivalent of this?  I'm converting some
old Perl code.

Even the Python FTP module doesn't have a directory parser.

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


Re: Queue cleanup

2010-08-11 Thread Paul Rubin
EW  writes:
> I thought about doing it that way and I could do it that way but it
> still seems like there should be a way to clean up Queues on my own.
> If I did it this way then I guess I'd be relying on garbage collection
> when the script ended to clean up the Queues for me.

Oh, I see.  As long as it's possible to start new producer or consumer
threads that touch a queue, obviously that queue has to still be around.
If the program starts all its threads at the beginning, then runs til
they exit, then does more stuff, then you could do something like:

# make dictonary of queues, one queue per task type
queues = {'sql': Queue(), 'logging': Queue(), ... }

for i in 
   threading.Thread(target=your_handler, args=[queues])

del queues

and then when all the threads exit, there are no remaining references to
the queues.  But why do you care?  Queues aren't gigantic structures,
they're just a list (collections.deque) with an rlock.  It's fine to let
the gc clean them up; that's the whole point of having a gc in the first
place.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to swallow traceback message

2010-08-11 Thread Tim Harig
On 2010-08-11, Back9  wrote:
> On Aug 11, 11:19 am, Tim Harig  wrote:
>> On 2010-08-11, Back9  wrote:
>> > But when I try to exit it, normally I use Ctrl+ C key to quit it.
>> > Problem is every time I do like it, it shows Traceback message and it
>> > makes my app not professional.
>>
>> You have three options.
>>
>>         1. Exit more properly.
>>
>>         2. Catch and handle SIGINT yourself.
>>
>>         3. Wrap whatever section of your program is being interrupted in
>>                 try/except to catch the KeyboardInterrupt exception when it
>>                 is generated.
>
> I should have mentioned that I already use try/except
> KeyboardInterrupt statement.
> But it does not seem to work as I expected.

The either your code is somewhere outside of the try/except block when
it receives SIGINT, the exception is being caught somewhere below the
try/except clause that you added for KeyboardInterrupt,  or there is
something wrong with your handling code.  If you want much more help,
you are going to have to post some code to give us some specifics to
troubleshoot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-11 Thread EW
On Aug 11, 1:55 pm, MRAB  wrote:
> EW wrote:
>
> [snip]
>
>
>
> > So here the P2 thread has ended and gone away but I still have his
> > Queue lingering.
>
> > So on a thread I can use is_alive() to check status and use join() to
> > clean up but I don't see any analogous functionality for Queues.  How
> > do I kill them?  I thought about putting a suicide message on the
> > Queue and then C1 would read it and set the variable to None but i'm
> > not sure setting the variable to None actually makes the Queue go
> > away.  It could just end up sitting in memory unreferenced - and
> > that's not good.  Additionally, I could have any number of consumer
> > threads reading that Queue so once the first one get the suicide note
> > the other consumer threads never would.
>
> > I figure there has to be an elegant way for managing my Queues but so
> > far I can't find it.  Any suggestions would be appreciated and thanks
> > in advance for any help.
>
> An object will be available for garbage collection when nothing refers
> to it either directly or indirectly. If it's unreferenced then it will
> go away.
>
> As for the suicide note, if a consumer sees it then it can put it back
> into the queue so other consumers will see it and then forget about the
> queue (set the variable which refers to the queue to None, or, if the
> references are in a list, delete it from the list).

Ok great.  I wasn't sure about the Garbage collection part of it.
That's actually pretty easy.

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


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread Tim Harig
On 2010-08-11, RG  wrote:
> I'm writing a system in a different language but want to use a Python 
> library.  I know of lots of ways to do this (embed a Python interpreter, 
> fire up a python server) but by far the easiest to implement is to have 
> the main program spawn a Python interpreter and interact with it through 
> its stdin/stdout.

Or, open python using a socket.  That way you have total control over how
the information is transfered, as well as bi-directional transfer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-11 Thread MRAB

EW wrote:
[snip]

So here the P2 thread has ended and gone away but I still have his
Queue lingering.

So on a thread I can use is_alive() to check status and use join() to
clean up but I don't see any analogous functionality for Queues.  How
do I kill them?  I thought about putting a suicide message on the
Queue and then C1 would read it and set the variable to None but i'm
not sure setting the variable to None actually makes the Queue go
away.  It could just end up sitting in memory unreferenced - and
that's not good.  Additionally, I could have any number of consumer
threads reading that Queue so once the first one get the suicide note
the other consumer threads never would.

I figure there has to be an elegant way for managing my Queues but so
far I can't find it.  Any suggestions would be appreciated and thanks
in advance for any help.


An object will be available for garbage collection when nothing refers
to it either directly or indirectly. If it's unreferenced then it will
go away.

As for the suicide note, if a consumer sees it then it can put it back
into the queue so other consumers will see it and then forget about the
queue (set the variable which refers to the queue to None, or, if the
references are in a list, delete it from the list).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is ElementTree development still active?

2010-08-11 Thread Terry Reedy

On 8/11/2010 12:21 PM, Pinku Surana wrote:

I checked the svn repo at effbot.org, but it appears to have no
updates since 2007. Has development moved elsewhere?


It is now in the stdlib (19.11) as xml.etree.ElementTree
http://svn.python.org/view/python/branches/py3k/Modules/_elementtree.c?revision=83949&view=markup
last revised 12 min ago.

--
Terry Jan Reedy

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


Re: Confused: Newbie Function Calls

2010-08-11 Thread Terry Reedy

Rather than patch your code, I think you should see a better approach.

from textwrap import dedent # removes common whitespace prefix

lines = []

def add_header(ss):
"Add header to sequence of string lines"
ss.append(dedent("""\ # No initial blank line
my multi-line
string here
"""))

def add_more(ss):
"Add more to sequence of string lines"
ss.append(dedent(""" # Start with blank line
another
multi-line
string here
"""))

add_header(lines)
add_more(lines)

print(''.join(lines)) # prints

my multi-line
string here

another
multi-line
string here



PS. Only use 'gen' for naming generator functions when you get to them.
--
Terry Jan Reedy

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


Re: Queue cleanup

2010-08-11 Thread EW
On Aug 11, 1:18 pm, Paul Rubin  wrote:
> EW  writes:
> > I also might have different consumer threads do
> > different tasks (for example one might write to a log and one might
> > write to SQL) so that again means I can't plan for a set ratio of
> > consumers to producers  So it's unknown.
>
> > So this means that instead of having 1 Queue that all the producers
> > put to and that all the consumers get from I actually have 1 Queue per
> > producer thread
>
> That doesn't sound appropriate.  Queues can have many readers and many
> writers.  So use one queue per task (logging, SQL, etc), regardless of
> the number of producer or consumer threads.  Any producer with an SQL
> request sends it to the SQL queue, which can have many listeners.  The
> different SQL consumer threads listen to the SQL queue and pick up
> requests and handle them.

I thought about doing it that way and I could do it that way but it
still seems like there should be a way to clean up Queues on my own.
If I did it this way then I guess I'd be relying on garbage collection
when the script ended to clean up the Queues for me.

What if I want to clean up my own Queues?  Regardless of the specifics
of my current design, I'm just generally curious how people manage
cleanup of their Queues when they don't want them any more.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysqldb - parameter issue

2010-08-11 Thread bruce
hey dennis...

umm.. given that i'm building the ins var/string to insert into the
execute... i can't just place the triple quotes around it..

are you saying that the execute should have quotes placed around it
within the execute
so it would be something like
 execute("\""+sel""\""...

or are you saying that within python i can just extend the line for
the "sel" on multiple lines..

as to the err.
  i'm getting a " >>> Warning: Data truncated for column

it appears that if i place the >>from_unixtime(%s) << at the end of
the paramaters, then everything works.. but if i place it within the
"%s" block.. the error is generated.

I'm assuming there's some way to wrap the from_unixtime(%s) so it
could be used as

%s,%s,%s, from_unixtime(%s), %s, %s,...

in checking the docs/spec.. i didn't see anything that discussed this...

thanks


>ins = """insert into functionError_TBL
>(errorStatus, CollegeID, processTime)
>values (%s, %s, from_unixtime(%s) )"""
>


On Wed, Aug 11, 2010 at 9:53 AM, Dennis Lee Bieber
 wrote:
> On Wed, 11 Aug 2010 08:08:21 -0700, bruce 
> declaimed the following in gmane.comp.python.general:
>
>
>>   tlist= [(1, 1, 1281502771)]
>>
>>   ins="insert into functionError_TBL "
>>   ins=ins+"(errorStatus, CollegeID, processTime)"
>>   ins=ins+" values "
>>   ins=ins+"  (%s,%s,  from_unixtime(%s))"
>
>        Without examining the rest of the problem, the above sequence can be
> cleaned up by using triple quotes...
>
>        ins = """insert into functionError_TBL
>                                        (errorStatus, CollegeID, processTime)
>                        values (%s, %s, from_unixtime(%s) )"""
>
>>
>> along with the corresponding insert portion, and the test list, an
>> error is generated..
>>
>        What error? You've failed to post the most important part... EXACTLY
> what the system reports...
> --
>        Wulfraed                 Dennis Lee Bieber         AF6VN
>        wlfr...@ix.netcom.com    HTTP://wlfraed.home.netcom.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Queue cleanup

2010-08-11 Thread Paul Rubin
EW  writes:
> I also might have different consumer threads do
> different tasks (for example one might write to a log and one might
> write to SQL) so that again means I can't plan for a set ratio of
> consumers to producers  So it's unknown.
>
> So this means that instead of having 1 Queue that all the producers
> put to and that all the consumers get from I actually have 1 Queue per
> producer thread 

That doesn't sound appropriate.  Queues can have many readers and many
writers.  So use one queue per task (logging, SQL, etc), regardless of
the number of producer or consumer threads.  Any producer with an SQL
request sends it to the SQL queue, which can have many listeners.  The
different SQL consumer threads listen to the SQL queue and pick up
requests and handle them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused: Newbie Function Calls

2010-08-11 Thread Dave Angel

fuglyducky wrote:

I am a complete newbie to Python (and programming in general) and I
have no idea what I'm missing. Below is a script that I am trying to
work with and I cannot get it to work. When I call the final print
function, nothing prints. However, if I print within the individual
functions, I get the appropriate printout.

Am I missing something??? Thanks in advance


# Global variable
sample_string = ""

def gen_header(sample_string):
HEADER = """
mymultilinestringhere
"""

sample_string += HEADER
return sample_string

def gen_nia(sample_string):
NIA = """
anothermultilinestringhere
"""

sample_string += NIA
return sample_string


gen_header(sample_string)
gen_nia(sample_string)

print(sample_string)

  
It'd be best if you used different names for global scope than you do 
inside your functions.  It won't change how this case works, but at 
least it'd be clearer what's happening.  And sometimes you can get an 
unintended side effect when you use the same name for two different 
variables.


In function gen_header(), you take an argument, and return a modified 
version of it.  But the call to it never uses the return value.  If you 
want to make any changes to the global value, you'd do something like this:


sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)

print(sample_string)


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


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread RG
In article ,
 Peter Otten <__pete...@web.de> wrote:

> Grant Edwards wrote:
> 
> > On 2010-08-11, Tim Harig  wrote:
> >> On 2010-08-11, RG  wrote:
> >>> When stdin is not a tty, Python seems to buffer all the input through
> >>> EOF before processing any of it:
> >>>
> >>> [...@mickey:~]$ cat | python
> >>> print 123
> >>> print 456 
> >>> 123
> >>> 456
> >>>
> >>> Is there a way to get Python to process input line-by-line the way it
> >>> does when stdin is a TTY even when stdin is not a TTY?
> >>
> >> It would be much better to know the overall purpose of what you are
> >> trying
> >> to achieve.  There are may be better ways (ie, sockets) depending what
> >> you
> >> are trying to do.  Knowing your target platform would also be helpful.
> >>
> >> For the python interpeter itself, you can can get interactive behavior by
> >> invoking it with the -i option.
> > 
> > If you're talking about unbuffered stdin/stdout, the option is -u.
> > 
> > I don't really see how the -i option is relevent -- it causes the
> > interpreter to go into interactive mode after running the script.
> 
> I'd say the following looks like what the OP was asking for:
> 
> $ cat | python -i -c'import sys; sys.ps1=""'
> print sys.stdin.isatty()
> False
> print 1
> 1
> print 2
> 2

That is indeed the behavior I'm looking for.

> (Whether it's useful is yet another question)

It's useful to me :-)  I'm trying to access a python library from a 
program written in another language for which an equivalent library is 
not available.  The easiest way to do that is to spawn a Python 
interpreter and interact with it through stdin/stdout.

Thanks!

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


Re: Queue cleanup

2010-08-11 Thread EW
On Aug 11, 12:55 pm, EW  wrote:
> Hi
>
> I'm writing a multithreaded app that relies on Queues to move data
> between the threads.  I'm trying to write my objects in a general way
> so that I can reuse them in the future so I need to write them in such
> a way that I don't know how many producer and how many consumer
> threads I might need.  I also might have different consumer threads do
> different tasks (for example one might write to a log and one might
> write to SQL) so that again means I can't plan for a set ratio of
> consumers to producers.  So it's unknown.
>
> So this means that instead of having 1 Queue that all the producers
> put to and that all the consumers get from I actually have 1 Queue per
> producer thread  that the main body sends to the correct type of
> consumer thread.  So I could get something like this where 3 producer
> threads write to 3 different Queues all of which get read by 1
> consumer thread:
>
> P1    P2   P3
>      \    |   /
>        \  |  /
>         C1
>
> So producers 1, 2, and 3 all write to individual Queues and consumer 1
> had a list of those Queues and reads them all.  The problem I'm having
> is that those producer threads can come and go pretty quickly and when
> they die I can cleanup the thread with join() but I'm still left with
> the Queue.  So I could get something like this:
>
> P1         P3
>      \    |   /
>        \  |  /
>         C1
>
> So here the P2 thread has ended and gone away but I still have his
> Queue lingering.
>
> So on a thread I can use is_alive() to check status and use join() to
> clean up but I don't see any analogous functionality for Queues.  How
> do I kill them?  I thought about putting a suicide message on the
> Queue and then C1 would read it and set the variable to None but i'm
> not sure setting the variable to None actually makes the Queue go
> away.  It could just end up sitting in memory unreferenced - and
> that's not good.  Additionally, I could have any number of consumer
> threads reading that Queue so once the first one get the suicide note
> the other consumer threads never would.
>
> I figure there has to be an elegant way for managing my Queues but so
> far I can't find it.  Any suggestions would be appreciated and thanks
> in advance for any help.
>
> ps Python rocks.

Whoo..the formatting got torn up!  My terrible diagrams are even more
terrible!  Oh well, I think you'll catch my meaning   :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Line-by-line processing when stdin is not a tty

2010-08-11 Thread RG
In article ,
 Cameron Simpson  wrote:

> On 11Aug2010 00:11, RG  wrote:
> | When stdin is not a tty, Python seems to buffer all the input through 
> | EOF before processing any of it:
> | 
> | [...@mickey:~]$ cat | python
> | print 123
> | print 456 
> | 123
> | 456
> | 
> | Is there a way to get Python to process input line-by-line the way it 
> | does when stdin is a TTY even when stdin is not a TTY?
> 
> What you're seeing here is not python's behaviour but cat's behaviour.
>
> Almost all programs do line buffering (flush buffer at newline) when the
> file is a terminal (character device) and block buffering (flush when a
> fixed size buffer, typically 8192 bytes or some larger power of 2) when
> the file is not a terminal. This is default behaviour for the stdio
> package.
> 
> So "cat" is simply not feeding any data to python until it has a lot of
> it;

I don't think that's right:

[...@mickey:~]$ cat | cat
123
123
321
321

Cat seems to flush its buffer after every newline.  Also:

[...@mickey:~]$ cat -u | python
print 123
print 456
123
456


> We would need to know
> more about your specific task to suggest workarounds.

I'm writing a system in a different language but want to use a Python 
library.  I know of lots of ways to do this (embed a Python interpreter, 
fire up a python server) but by far the easiest to implement is to have 
the main program spawn a Python interpreter and interact with it through 
its stdin/stdout.  In my code I explicitly force the output stream that 
is being piped to Python's stdin to be flushed so I know it's not a 
buffering problem on the input side.

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


Re: Confused: Newbie Function Calls

2010-08-11 Thread EW
On Aug 11, 12:39 pm, fuglyducky  wrote:
> On Aug 11, 9:31 am, Pinku Surana  wrote:
>
>
>
>
>
> > On Aug 11, 12:07 pm, fuglyducky  wrote:
>
> > > I am a complete newbie to Python (and programming in general) and I
> > > have no idea what I'm missing. Below is a script that I am trying to
> > > work with and I cannot get it to work. When I call the final print
> > > function, nothing prints. However, if I print within the individual
> > > functions, I get the appropriate printout.
>
> > > Am I missing something??? Thanks in advance
>
> > > 
> > > # Global variable
> > > sample_string = ""
>
> > > def gen_header(sample_string):
> > >     HEADER = """
> > >     mymultilinestringhere
> > >     """
>
> > >     sample_string += HEADER
> > >     return sample_string
>
> > > def gen_nia(sample_string):
> > >     NIA = """
> > >     anothermultilinestringhere
> > >     """
>
> > >     sample_string += NIA
> > >     return sample_string
>
> > > gen_header(sample_string)
> > > gen_nia(sample_string)
>
> > > print(sample_string)
>
> > There are 2 problems with your program.
>
> > (1) If you want to use a global variable in a function, you have to
> > add the line "global sample_string" to the beginning of that
> > function.
>
> > (2) Once you do (1), you will get an error because you've got
> > sample_string as a global and a function parameter. Which one do you
> > want to use in the function? You should change the name of the
> > parameter to "sample" to solve that confusion.
>
> > Here's the result, which works for me:
>
> > sample_string = ""
> > def gen_header(sample):
> >     global sample_string
> >     HEADER = """
> >     mymultilinestringhere
> >     """
> >     sample_string = sample + HEADER
> >     return sample_string
> > def gen_nia(sample):
> >     global sample_string
> >     NIA = """
> >     anothermultilinestringhere
> >     """
> >     sample_string = sample + NIA
> >     return sample_string
> > gen_header(sample_string)
> > gen_nia(sample_string)
> > print(sample_string)
>
> Thanks! That did the trick.
>
> I am a bit confused though. I tried to follow a sample in a book
> (which works) where I didn't have to 1) pass the global variable as a
> parameter into the function, 2) did not have to define the global
> variable within the function. I apologize if this is a super stupid
> question but if it is global, why do I have to pass it into the
> function? Shouldn't the global variable be accessible from anywhere???

If it's a global then you don't have to pass it to the function but
you do have to have the line that says:
global sample_string


Now if you think the example in the book didn't do that and it still
worked then if you post that sample I'm sure somebody can tell you why
it worked.  The book example might be doing something different.
-- 
http://mail.python.org/mailman/listinfo/python-list


Queue cleanup

2010-08-11 Thread EW
Hi

I'm writing a multithreaded app that relies on Queues to move data
between the threads.  I'm trying to write my objects in a general way
so that I can reuse them in the future so I need to write them in such
a way that I don't know how many producer and how many consumer
threads I might need.  I also might have different consumer threads do
different tasks (for example one might write to a log and one might
write to SQL) so that again means I can't plan for a set ratio of
consumers to producers.  So it's unknown.

So this means that instead of having 1 Queue that all the producers
put to and that all the consumers get from I actually have 1 Queue per
producer thread  that the main body sends to the correct type of
consumer thread.  So I could get something like this where 3 producer
threads write to 3 different Queues all of which get read by 1
consumer thread:

P1P2   P3
 \|   /
   \  |  /
C1

So producers 1, 2, and 3 all write to individual Queues and consumer 1
had a list of those Queues and reads them all.  The problem I'm having
is that those producer threads can come and go pretty quickly and when
they die I can cleanup the thread with join() but I'm still left with
the Queue.  So I could get something like this:

P1 P3
 \|   /
   \  |  /
C1

So here the P2 thread has ended and gone away but I still have his
Queue lingering.

So on a thread I can use is_alive() to check status and use join() to
clean up but I don't see any analogous functionality for Queues.  How
do I kill them?  I thought about putting a suicide message on the
Queue and then C1 would read it and set the variable to None but i'm
not sure setting the variable to None actually makes the Queue go
away.  It could just end up sitting in memory unreferenced - and
that's not good.  Additionally, I could have any number of consumer
threads reading that Queue so once the first one get the suicide note
the other consumer threads never would.

I figure there has to be an elegant way for managing my Queues but so
far I can't find it.  Any suggestions would be appreciated and thanks
in advance for any help.


ps Python rocks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused: Newbie Function Calls

2010-08-11 Thread Jean-Michel Pichavant

fuglyducky wrote:

I am a complete newbie to Python (and programming in general) and I
have no idea what I'm missing. Below is a script that I am trying to
work with and I cannot get it to work. When I call the final print
function, nothing prints. However, if I print within the individual
functions, I get the appropriate printout.

Am I missing something??? Thanks in advance


# Global variable
sample_string = ""

def gen_header(sample_string):
HEADER = """
mymultilinestringhere
"""

sample_string += HEADER
return sample_string

def gen_nia(sample_string):
NIA = """
anothermultilinestringhere
"""

sample_string += NIA
return sample_string


gen_header(sample_string)
gen_nia(sample_string)

print(sample_string)
  

sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)

print sample_string

That should work.

I guess you made an error thinking that

sample_string += HEADER

would change the value of the given parameter. It does not. The value is 
changed only for sample_string within the function This is the case for 
any immutable object (strings are immutable) in Python.


Example:


class AMutable(object):
   def __init__(self):
   self.description = 'I am X'

myString = 'I am a immutable string' # an immutable object
myMutable = AMutable() # a mutable object

def bar(myMutable):
   myMutable.description = 'I am Y' # change the attribute description 
of the object


def foo(aString):
   aString = 'fo' # will have no effect outside the function

print 'before calling bar: ', myMutable.description
bar(myMutable)
print 'after calling bar: ', myMutable.description
print 'before calling foo: ', myString
foo(myString)
print 'after calling foo: ', myString


>
before calling bar:  I am X
after calling bar:  I am Y
before calling foo:  I am a immutable string
after calling foo:  I am a immutable string

cheers,

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


Re: Confused: Newbie Function Calls

2010-08-11 Thread Wieland Hoffmann
On 11.08.2010 18:07, fuglyducky wrote:
> Am I missing something??? Thanks in advance
Assign the returned value of your functions to something (like
sample_string) and it will work:
> 
> # Global variable
> sample_string = ""
> 
> def gen_header(sample_string):
> HEADER = """
> mymultilinestringhere
> """
> 
> sample_string += HEADER
> return sample_string
> 
> def gen_nia(sample_string):
> NIA = """
> anothermultilinestringhere
> """
> 
> sample_string += NIA
> return sample_string
> 
> 
> sample_string = gen_header(sample_string)
> sample_string = gen_nia(sample_string)
> 
> print(sample_string)

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


Re: Confused: Newbie Function Calls

2010-08-11 Thread fuglyducky
On Aug 11, 9:31 am, Pinku Surana  wrote:
> On Aug 11, 12:07 pm, fuglyducky  wrote:
>
>
>
> > I am a complete newbie to Python (and programming in general) and I
> > have no idea what I'm missing. Below is a script that I am trying to
> > work with and I cannot get it to work. When I call the final print
> > function, nothing prints. However, if I print within the individual
> > functions, I get the appropriate printout.
>
> > Am I missing something??? Thanks in advance
>
> > 
> > # Global variable
> > sample_string = ""
>
> > def gen_header(sample_string):
> >     HEADER = """
> >     mymultilinestringhere
> >     """
>
> >     sample_string += HEADER
> >     return sample_string
>
> > def gen_nia(sample_string):
> >     NIA = """
> >     anothermultilinestringhere
> >     """
>
> >     sample_string += NIA
> >     return sample_string
>
> > gen_header(sample_string)
> > gen_nia(sample_string)
>
> > print(sample_string)
>
> There are 2 problems with your program.
>
> (1) If you want to use a global variable in a function, you have to
> add the line "global sample_string" to the beginning of that
> function.
>
> (2) Once you do (1), you will get an error because you've got
> sample_string as a global and a function parameter. Which one do you
> want to use in the function? You should change the name of the
> parameter to "sample" to solve that confusion.
>
> Here's the result, which works for me:
>
> sample_string = ""
> def gen_header(sample):
>     global sample_string
>     HEADER = """
>     mymultilinestringhere
>     """
>     sample_string = sample + HEADER
>     return sample_string
> def gen_nia(sample):
>     global sample_string
>     NIA = """
>     anothermultilinestringhere
>     """
>     sample_string = sample + NIA
>     return sample_string
> gen_header(sample_string)
> gen_nia(sample_string)
> print(sample_string)

Thanks! That did the trick.

I am a bit confused though. I tried to follow a sample in a book
(which works) where I didn't have to 1) pass the global variable as a
parameter into the function, 2) did not have to define the global
variable within the function. I apologize if this is a super stupid
question but if it is global, why do I have to pass it into the
function? Shouldn't the global variable be accessible from anywhere???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused: Newbie Function Calls

2010-08-11 Thread EW
This will work:

sample_string=""

def gen_header(sample_string=""):
HEADER = """
mymultilinestringhere
"""

sample_string+= HEADER
return sample_string

def gen_nia(sample_string=""):

NIA = """
anothermultilinestringhere
"""
sample_string += NIA
return sample_string

sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)
print(sample_string)


and this will work


sample_string=""

def gen_header(OtherString):
global sample_string
HEADER = """
mymultilinestringhere
"""

sample_string+= HEADER


def gen_nia(OtherString):
global sample_string
NIA = """
anothermultilinestringhere
"""
sample_string += NIA


gen_header(sample_string)
gen_nia(sample_string)
print(sample_string)




The first one is the better of the 2 in this example but the second
one will show you how to use global variables if you really need to
use them

So your problem was that you thought you were working on a global
variable in your functions when you were not.  Since the your def
lines contained sample_string that make it a local variable.  So when
you were doing your += statements you were working on a local variable
and not a global variable.  You were returning the value of the local
variable but you didn't have anything in the main body of your script
catching that value.  So simply changing these 2 lines:
sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)

made the global sample_string variable store the values of the return
data.


If you want to use global variables then you just have to do 2
things.  First you have to make sure you don't have any local
variables it the function with the same name.  So I change the name to
OtherString in the def line.  Then you need a global statement at the
start of your function (global sample_string) that tells python that
you really do want to use that global variable.

Global variables can cause you no end of heartache so python forces
you to explicitly state that you want to use them.

Hope that helps.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused: Newbie Function Calls

2010-08-11 Thread Pinku Surana
On Aug 11, 12:07 pm, fuglyducky  wrote:
> I am a complete newbie to Python (and programming in general) and I
> have no idea what I'm missing. Below is a script that I am trying to
> work with and I cannot get it to work. When I call the final print
> function, nothing prints. However, if I print within the individual
> functions, I get the appropriate printout.
>
> Am I missing something??? Thanks in advance
>
> 
> # Global variable
> sample_string = ""
>
> def gen_header(sample_string):
>     HEADER = """
>     mymultilinestringhere
>     """
>
>     sample_string += HEADER
>     return sample_string
>
> def gen_nia(sample_string):
>     NIA = """
>     anothermultilinestringhere
>     """
>
>     sample_string += NIA
>     return sample_string
>
> gen_header(sample_string)
> gen_nia(sample_string)
>
> print(sample_string)

There are 2 problems with your program.

(1) If you want to use a global variable in a function, you have to
add the line "global sample_string" to the beginning of that
function.

(2) Once you do (1), you will get an error because you've got
sample_string as a global and a function parameter. Which one do you
want to use in the function? You should change the name of the
parameter to "sample" to solve that confusion.

Here's the result, which works for me:

sample_string = ""
def gen_header(sample):
global sample_string
HEADER = """
mymultilinestringhere
"""
sample_string = sample + HEADER
return sample_string
def gen_nia(sample):
global sample_string
NIA = """
anothermultilinestringhere
"""
sample_string = sample + NIA
return sample_string
gen_header(sample_string)
gen_nia(sample_string)
print(sample_string)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused: Newbie Function Calls

2010-08-11 Thread Robert Kern

On 8/11/10 11:07 AM, fuglyducky wrote:

I am a complete newbie to Python (and programming in general) and I
have no idea what I'm missing. Below is a script that I am trying to
work with and I cannot get it to work. When I call the final print
function, nothing prints. However, if I print within the individual
functions, I get the appropriate printout.

Am I missing something??? Thanks in advance


# Global variable
sample_string = ""

def gen_header(sample_string):
 HEADER = """
 mymultilinestringhere
 """

 sample_string += HEADER
 return sample_string


By default, all assignments inside of a function are local to the function. Even 
augmented assignments like +=. Python strings are immutable, so


  sample_string += HEADER

works exactly like

  sample_string = sample_string + HEADER

The string referred to by the global name sample_string is never modified and 
the global name is never reassigned.


http://docs.python.org/py3k/tutorial/classes.html#python-scopes-and-namespaces


gen_header(sample_string)
gen_nia(sample_string)

print(sample_string)


You probably want something like the following:

sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)

print(sample_string)

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Confused: Newbie Function Calls

2010-08-11 Thread Michael Torrie
On 08/11/2010 10:07 AM, fuglyducky wrote:
> I am a complete newbie to Python (and programming in general) and I
> have no idea what I'm missing. Below is a script that I am trying to
> work with and I cannot get it to work. When I call the final print
> function, nothing prints. However, if I print within the individual
> functions, I get the appropriate printout.
> 
> Am I missing something??? Thanks in advance

Yes.  You are passing sample_string into the functions, but not doing
anything with the return value.

> def gen_header(sample_string):
   ^^^
The sample_string name is rebound to the parameter now, completely
hiding the global variable, if that's really what you wanted.

> def gen_nia(sample_string):
   ^^^
Again.

> NIA = """
> anothermultilinestringhere
> """
> 
> sample_string += NIA
> return sample_string
> 
> 
> gen_header(sample_string)
> gen_nia(sample_string)

Try this:

sample_string = gen_header(sample_string)
sample_string = gen_nia(sample_string)

You could drop the arguments to your functions and use the "global"
keyword to get access to sample_string from within the functions, but
normally that's a bad idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is ElementTree development still active?

2010-08-11 Thread Pinku Surana
I checked the svn repo at effbot.org, but it appears to have no
updates since 2007. Has development moved elsewhere?

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


Re: type enforcement in _ssl.sslwrap

2010-08-11 Thread Eric Snow
On Aug 11, 5:34 am, Steven D'Aprano  wrote:
> On Tue, 10 Aug 2010 10:40:54 -0700, Eric Snow wrote:
> > ssl.SSLSocket.__init__ makes a call to _ssl.sslwrap (in the C module).
> > That in turn makes a call to PyArg_ParseTuple, which casts the first arg
> > of _ssl.sslwrap into a PySocketModule.Sock_Type object.
>
> > My problem is that I am trying to pass in an object that implements the
> > Socket interface, but does not inherit from _socket.socket, like you do
> > with file-like objects.  Is there a way to make this work, or is the
> > PyArg_ParseTuple call going to stop me.
>
> I don't know. What happens when you try it?
>
> --
> Steven

When I pass my socket object in to ssl.wrap_socket I get the following
exception:

Traceback (most recent call last):
  File "", line 1, in 
  ...
  File "/usr/local/lib/python2.7/ssl.py", line 342, in wrap_socket
ciphers=ciphers)
  File "/usr/local/lib/python2.7/ssl.py", line 119, in __init__
ciphers)
TypeError: must be _socket.socket, not ClientSocket

I looked at what is going on there and found the call to
_ssl.sslwrap.  I tracked it down in the C source and found the call to
PyArg_ParseTuple.

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


Confused: Newbie Function Calls

2010-08-11 Thread fuglyducky
I am a complete newbie to Python (and programming in general) and I
have no idea what I'm missing. Below is a script that I am trying to
work with and I cannot get it to work. When I call the final print
function, nothing prints. However, if I print within the individual
functions, I get the appropriate printout.

Am I missing something??? Thanks in advance


# Global variable
sample_string = ""

def gen_header(sample_string):
HEADER = """
mymultilinestringhere
"""

sample_string += HEADER
return sample_string

def gen_nia(sample_string):
NIA = """
anothermultilinestringhere
"""

sample_string += NIA
return sample_string


gen_header(sample_string)
gen_nia(sample_string)

print(sample_string)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regex to remove lines made of only whitespace

2010-08-11 Thread Chris Withers

Steven D'Aprano wrote:

def strip_blank_lines(lines):
for line in lines:
if not line.isspace():
yield line

text = ''.join(strip_blank_lines(lines.split('\n')))


The final version I have is:

def strip_blank_lines(text):
result = []
for line in text.split('\n'):
if line and not line.isspace():
result.append(line)
return '\n'.join(result)

Any improvements would be very welcome!

Chris

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


Re: How to swallow traceback message

2010-08-11 Thread Michael Torrie
On 08/11/2010 09:32 AM, Back9 wrote:
> I should have mentioned that I already use try/except
> KeyboardInterrupt statement.
> But it does not seem to work as I expected.

If you want anyone to help further, you will need to say a) what you are
expecting it to do and b) what it is actually doing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to swallow traceback message

2010-08-11 Thread Back9

On Aug 11, 11:19 am, Tim Harig  wrote:
> On 2010-08-11, Back9  wrote:
>
> > python myapp.py input_file | more
> > to see them step by step.
>
> > But when I try to exit it, normally I use Ctrl+ C key to quit it.
> > Problem is every time I do like it, it shows Traceback message and it
> > makes my app not professional.
>
> You have three options.
>
>         1. Exit more properly.
>
>         2. Catch and handle SIGINT yourself.
>
>         3. Wrap whatever section of your program is being interrupted in
>                 try/except to catch the KeyboardInterrupt exception when it
>                 is generated.

I should have mentioned that I already use try/except
KeyboardInterrupt statement.
But it does not seem to work as I expected.

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


Re: How to swallow traceback message

2010-08-11 Thread Jean-Michel Pichavant

Back9 wrote:

Hi,

I run my py app to display a file's contents, and it is normally very
long.
So I use it like below:

python myapp.py input_file | more
to see them step by step.

But when I try to exit it, normally I use Ctrl+ C key to quit it.
Problem is every time I do like it, it shows Traceback message and it
makes my app not professional.

How do I handle it gracefully.

TIA
  

if __name__ == '__main__':
   try:
  main()
   except KeyboardInterrupt:
  print 'Hey ! this is a professional application'

Cheers,

JM



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


Re: How to swallow traceback message

2010-08-11 Thread Eknath Venkataramani
See Exception Handling 

On Wed, Aug 11, 2010 at 11:09 AM, Back9  wrote:

> Hi,
>
> I run my py app to display a file's contents, and it is normally very
> long.
> So I use it like below:
>
> python myapp.py input_file | more
> to see them step by step.
>
> But when I try to exit it, normally I use Ctrl+ C key to quit it.
> Problem is every time I do like it, it shows Traceback message and it
> makes my app not professional.
>
> How do I handle it gracefully.
>
> TIA
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: urgent requirement at Hyderabad

2010-08-11 Thread Chris Withers

sushma wrote:

  We are looking for Python Developers/programmers with 1+ years of
experience. Send resume to sush...@millenniumsoft.com


So urgent you can't even be bothered to describe the job or post the 
advert in the correct place on the python job board.


Good luck with that ;-)

Chris

--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to swallow traceback message

2010-08-11 Thread Tim Harig
On 2010-08-11, Back9  wrote:
> python myapp.py input_file | more
> to see them step by step.
>
> But when I try to exit it, normally I use Ctrl+ C key to quit it.
> Problem is every time I do like it, it shows Traceback message and it
> makes my app not professional.

You have three options.

1. Exit more properly.

2. Catch and handle SIGINT yourself.

3. Wrap whatever section of your program is being interrupted in
try/except to catch the KeyboardInterrupt exception when it
is generated.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >