Re: Defining a Python enum in a C extension - am I doing this right?

2021-08-03 Thread Sean DiZazzo
On Tuesday, August 3, 2021 at 3:04:19 AM UTC-7, Bartosz Golaszewski wrote:
> On Sat, Jul 31, 2021 at 3:01 PM Bartosz Golaszewski  wrote: 
> > 
> > On Fri, Jul 30, 2021 at 2:41 PM Serhiy Storchaka  wrote: 
> > > 
> > > 23.07.21 11:20, Bartosz Golaszewski пише: 
> > > > I'm working on a Python C extension and I would like to expose a 
> > > > custom enum (as in: a class inheriting from enum.Enum) that would be 
> > > > entirely defined in C. 
> > > 
> > > I think that it would be much easier to define it in Python, and then 
> > > either import a Python module in your C code, or exec a Python code as a 
> > > string. 
> > > 
> > 
> > You mean: evaluate a string like this: 
> > 
> > ''' 
> > import enum 
> > 
> > class FooBar(enum.Enum): 
> > FOO = 1 
> > BAR = 2 
> > BAZ = 3 
> > ''' 
> > 
> > And then pull in the FooBar type from the resulting dictionary into my 
> > C code? Sounds good actually. I think I'll be able to add the FooBar 
> > type to another type's tp_dict too - because some enums I want to 
> > create will be nested in other classes. 
> > 
> > Bart
> Just a follow-up: this is how I did it eventually: 
> 
> ``` 
> #include  
> 
> typedef struct { 
> PyObject_HEAD; 
> } dummy_object; 
> 
> PyDoc_STRVAR(dummy_type_doc, "Dummy type in which the enum will be nested."); 
> 
> static PyTypeObject dummy_type = { 
> PyVarObject_HEAD_INIT(NULL, 0) 
> .tp_name = "pycenum.DummyType", 
> .tp_basicsize = sizeof(dummy_object), 
> .tp_flags = Py_TPFLAGS_DEFAULT, 
> .tp_doc = dummy_type_doc, 
> .tp_new = PyType_GenericNew, 
> .tp_dealloc = (destructor)PyObject_Del, 
> };
> PyDoc_STRVAR(module_doc, 
> "C extension module defining a class inheriting from enum.Enum."); 
> 
> static PyModuleDef module_def = { 
> PyModuleDef_HEAD_INIT, 
> .m_name = "pycenum", 
> .m_doc = module_doc, 
> .m_size = -1, 
> };
> static int add_foobar_enum(PyObject *module) 
> { 
> static const char *foobar_src = 
> "class FooBar(enum.Enum):\n" 
> " FOO = 1\n" 
> " BAR = 2\n" 
> " BAZ = 3\n"; 
> 
> PyObject *main_mod, *main_dict, *enum_mod, *result, *foobar_type; 
> int ret; 
> 
> main_mod = PyImport_AddModule("__main__"); 
> if (!main_mod) 
> return -1; 
> 
> main_dict = PyModule_GetDict(main_mod); 
> if (!main_dict) { 
> Py_DECREF(main_mod); 
> return -1;
> } 
> 
> enum_mod = PyImport_ImportModule("enum");
> if (!enum_mod) { 
> Py_DECREF(main_mod); 
> return -1; 
> } 
> 
> ret = PyDict_SetItemString(main_dict, "enum", enum_mod); 
> Py_DECREF(enum_mod); 
> if (ret) { 
> Py_DECREF(main_mod); 
> return -1; 
> } 
> 
> result = PyRun_String(foobar_src, Py_single_input, 
> main_dict, main_dict); 
> if (!result) { 
> Py_DECREF(main_mod); 
> return -1; 
> } 
> 
> foobar_type = PyDict_GetItemString(main_dict, "FooBar"); 
> if (!foobar_type) { 
> Py_DECREF(main_mod); 
> return -1; 
> } 
> 
> ret = PyDict_SetItemString(dummy_type.tp_dict, "FooBar", foobar_type); 
> Py_DECREF(foobar_type); 
> Py_DECREF(main_mod); 
> if (ret) 
> return -1; 
> 
> PyType_Modified(&dummy_type); 
> 
> return ret; 
> } 
> 
> PyMODINIT_FUNC PyInit_pycenum(void) 
> { 
> PyObject *module;
> int ret; 
> 
> module = PyModule_Create(&module_def); 
> if (!module) 
> return NULL; 
> 
> ret = PyModule_AddStringConstant(module, "__version__", "0.0.1");
> if (ret) { 
> Py_DECREF(module); 
> return NULL; 
> } 
> 
> ret = PyType_Ready(&dummy_type); 
> if (ret) { 
> Py_DECREF(module); 
> return NULL; 
> } 
> 
> ret = add_foobar_enum(module); 
> if (ret) { 
> Py_DECREF(module); 
> return NULL; 
> } 
> 
> Py_INCREF(&dummy_type); 
> ret = PyModule_AddObject(module, "DummyType", (PyObject *)&dummy_type); 
> if (ret) { 
> Py_DECREF(&dummy_type);
> Py_DECREF(module); 
> return NULL; 
> } 
> 
> return module; 
> }
> ``` 
> 
> Bart
No
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Errno 2] No such file or directory:

2021-07-30 Thread Sean DiZazzo
On Thursday, July 29, 2021 at 7:42:58 AM UTC-7, joseph pareti wrote:
> indeed. There are better options than the one I attempted. Thanks for the 
> advice 
> 
> Am Mi., 28. Juli 2021 um 18:19 Uhr schrieb Chris Angelico  >:
> > On Thu, Jul 29, 2021 at 2:10 AM joseph pareti 
> > wrote: 
> > > 
> > > The following code fails as shown in the title: 
> > > 
> > > 
> > > 
> > > 
> > > 
> > > 
> > > *import subprocesscmd = 'ls -l 
> > > 
> > /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48
> >  
> > > | awk "{print $9 }"'process = subprocess.Popen([cmd],
> > > stdout=subprocess.PIPE, stderr=subprocess.PIPE)stdout, stderr = 
> > > process.communicate()print('stdout ',stdout)print('stderr ',stderr)* 
> > > 
> > >  
> > > 
> > > Traceback (most recent call last): 
> > > File "PreProcess_1a.py", line 3, in  
> > > process = subprocess.Popen([cmd], stdout=subprocess.PIPE, 
> > > stderr=subprocess.PIPE) 
> > > File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line 
> > 854, 
> > > in __init__ 
> > > self._execute_child(args, executable, preexec_fn, close_fds, 
> > > File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line 
> > > 1702, in _execute_child 
> > > raise child_exception_type(errno_num, err_msg, err_filename) 
> > > FileNotFoundError: [Errno 2] No such file or directory: 'ls -l 
> > > 
> > /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48
> >  
> > > | awk "{print $9 
> > > 
> >
> > First off, you'll want to post code in a way that keeps the 
> > formatting, otherwise it becomes very hard to read. 
> > 
> > But the immediate problem here is that Popen takes an array of command 
> > arguments, NOT a shell command line. You cannot invoke ls and pipe it 
> > into awk this way. 
> > 
> > Don't think like a shell script. Python has very good 
> > directory-listing functionality, and you will very very seldom need to 
> > shell out to pipelines. Figure out what you actually need to learn 
> > from the directory listing and get that information directly, rather 
> > than trying to use two external commands and text parsing. It's far 
> > FAR easier, cleaner, and safer that way. 
> > 
> > ChrisA
> > -- 
> > https://mail.python.org/mailman/listinfo/python-list
> > 
> 
> 
> -- 
> Regards, 
> Joseph Pareti - Artificial Intelligence consultant 
> Joseph Pareti's AI Consulting Services 
> https://www.joepareti54-ai.com/ 
> cell +49 1520 1600 209 
> cell +39 339 797 0644

I prefer LOLCODE for these kinds of tasks.

HAI 1.2
I HAS A VAR ITZ MAH_DIRECTORY
GIMMEH MAH_DIRECTORY

CAN HAS STDIO?
BOTH SAEM MAH_DIRECTORY AN 
"/media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48",
 O RLY?
  YA RLY, VISIBLE "FILEZ GO HERE!"
  NO WAI, VISIBLE "WTF IZ THAT?"
OIC

KTHXBYE
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: a simple question

2021-07-29 Thread Sean DiZazzo
On Tuesday, July 27, 2021 at 5:05:27 AM UTC-7, Terry Reedy wrote:
> On 7/26/2021 6:19 PM, Glenn Wilson via Python-list wrote: 
> > I recently downloaded the latest version of python, 3.9.6. Everything works 
> > except, the turtle module. I get an error message every time , I use basic 
> > commands like forward, backward, right and left. My syntax is correct: 
> > pat.forward(100) is an example. Can you tell me what is wrong.
> On Windows, normal install, 
> C:\Users\Terry>py -3.9 -m turtle 
> C:\Users\Terry>py -3.9 -m turtledemo 
> both work. 
> 
> 
> -- 
> Terry Jan Reedy

Welcome to programming!!  Ain't it fun?!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Create an alias to an attribute on superclass

2018-02-01 Thread Sean DiZazzo
On Thursday, February 1, 2018 at 10:23:06 AM UTC-8, Sean DiZazzo wrote:
> Hi!
> 
> I basically just want to create an alias to an attribute on an item's 
> superclass.  So that after I create the subclass object, I can access the 
> alias attribute to get the value back.
> 
> 
> class Superclass(object):
> def __init__(self, value):
> """
> I want to pass x by reference, so that any time
> x on the subclass is updated, so is the alias here
> """
> self.alias = value
> 
> class Subclass(Superclass):
> def __init__(self, x):
> self.x = x
> Superclass.__init__(self, self.x)
> 
> def __repr__(self):
> return "x: %s\nalias: %s" % (self.x, self.alias)
> 
> 
> if __name__ == "__main__":
> foo = Subclass(1)
> print foo.alias
> 
> foo.x = 6
> # Should return 6 !!!
> print foo.alias
> 
> 

Yep.  Thats it.  Thank you guys!!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Create an alias to an attribute on superclass

2018-02-01 Thread Sean DiZazzo
On Thursday, February 1, 2018 at 10:37:32 AM UTC-8, Chris Angelico wrote:
> On Fri, Feb 2, 2018 at 5:22 AM, Sean DiZazzo  wrote:
> > Hi!
> >
> > I basically just want to create an alias to an attribute on an item's 
> > superclass.  So that after I create the subclass object, I can access the 
> > alias attribute to get the value back.
> >
> > 
> > class Superclass(object):
> > def __init__(self, value):
> > """
> > I want to pass x by reference, so that any time
> > x on the subclass is updated, so is the alias here
> > """
> > self.alias = value
> >
> > class Subclass(Superclass):
> > def __init__(self, x):
> > self.x = x
> > Superclass.__init__(self, self.x)
> >
> > def __repr__(self):
> > return "x: %s\nalias: %s" % (self.x, self.alias)
> >
> >
> > if __name__ == "__main__":
> > foo = Subclass(1)
> > print foo.alias
> >
> > foo.x = 6
> > # Should return 6 !!!
> > print foo.alias
> >
> > 
> 
> ISTM the easiest way would be to define a property on the superclass:
> 
> class Superclass(object):
> @property
> def alias(self):
> return self.x
> 
> Whatever happens, self.alias will be identical to self.x. Is that what
> you're after?
> 
> ChrisA

Yes, but that doesn't seem to work.  It looks like there is a way to do it if 
you make the original value a list (mutable) instead of an integer.  I really 
need to do it with an arbitrary object.  Not sure if I can hack the list trick 
to work in my case though.
-- 
https://mail.python.org/mailman/listinfo/python-list


Create an alias to an attribute on superclass

2018-02-01 Thread Sean DiZazzo
Hi!

I basically just want to create an alias to an attribute on an item's 
superclass.  So that after I create the subclass object, I can access the alias 
attribute to get the value back.


class Superclass(object):
def __init__(self, value):
"""
I want to pass x by reference, so that any time
x on the subclass is updated, so is the alias here
"""
self.alias = value

class Subclass(Superclass):
def __init__(self, x):
self.x = x
Superclass.__init__(self, self.x)

def __repr__(self):
return "x: %s\nalias: %s" % (self.x, self.alias)


if __name__ == "__main__":
foo = Subclass(1)
print foo.alias

foo.x = 6
# Should return 6 !!!
print foo.alias


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


Re: "tkinter"

2017-09-13 Thread Sean DiZazzo
On Wednesday, September 13, 2017 at 7:21:25 PM UTC-7, Grant Edwards wrote:
> On 2017-09-13, Ben Finney  wrote:
> 
> > The toolkit in question is named “tk”, which I have only ever known to
> > be pronounced “tee kay”.
> >
> > The rest of the word is an abbreviation of “interface”.
> >
> > So, to me “Tkinter” is pronounced “tee kay inter”.
> 
> Same here.  Though I've probably said it aloud less than a half-dozen
> times in the past twenty-whatever years.
> 
> --
> Grant

I usually just say "tinker", since it's easy...knowing that it's wrong.  I 
agree with the "tee-kay" folks on correct pronunciation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: the core values of the Python "platform"

2017-09-13 Thread Sean DiZazzo
On Wednesday, September 13, 2017 at 6:16:58 AM UTC-7, leam hall wrote:
> On Wed, Sep 13, 2017 at 9:08 AM, Darin Gordon  wrote:
> 
> > Bryan Cantrill gave an interesting talk recently at a Node conference about
> > "platform values" [1]. The talk lead me to think about what the core values
> > of the Python "platform" are and I thought it would be good to ask this
> > question of the community. What would you consider the top (<= 5) core
> > values?
> >
> >
> Would that be close to the Zen of Python?

The Zen of Python says it all.

There might be some that argue with intricacies, but the core values are 
expressed clearly in it.  Some people just like to argue.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A good way to unpack a matrix

2017-09-13 Thread Sean DiZazzo
On Wednesday, September 13, 2017 at 7:53:25 PM UTC-7, Andrew Zyman wrote:
> hello,
>  is there a better approach to populating a function in this situation?
> 
> res = self.DB.getPrice():  # returns array of 3x2 always.  symbol_id,
> symbol, price.
> 
> var1 = self.AFunction(symbols=res[0][2] + '.' + res[1][2], conid1=
> self.Contracts[res[0][0]].conId,
> 
> conid2=self.Contracts[res[1][0]].conId, price1= res[0][2], price2=
> res[1][2])
> 
> 
> Thank you.

OOP?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python dress

2017-09-13 Thread Sean DiZazzo
On Wednesday, September 13, 2017 at 3:02:18 PM UTC-7, bream...@gmail.com wrote:
> On Wednesday, September 13, 2017 at 10:43:47 PM UTC+1, Sean DiZazzo wrote:
> > On Tuesday, September 12, 2017 at 9:18:12 AM UTC-7, larry@gmail.com 
> > wrote:
> > > Not too many females here, but anyway:
> > > 
> > > https://svahausa.com/collections/shop-by-interest-1/products/python-code-fit-flare-dress
> > > 
> > > (And if any guys want to wear this, there's nothing wrong with that.)
> > 
> > I'm going to buy it for my girl wear it to all of my work parties.  :)
> 
> What is she going to wear? :)
> 
> --
> Kindest regards.
> 
> Mark Lawrence.

She's gonna wear the geek dress with pride!  She knows.

There's a nice little Coco Chanel I have picked out for myself.  :P
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python dress

2017-09-13 Thread Sean DiZazzo
On Tuesday, September 12, 2017 at 9:18:12 AM UTC-7, larry@gmail.com wrote:
> Not too many females here, but anyway:
> 
> https://svahausa.com/collections/shop-by-interest-1/products/python-code-fit-flare-dress
> 
> (And if any guys want to wear this, there's nothing wrong with that.)

I'm going to buy it for my girl wear it to all of my work parties.  :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: rmtree message

2017-09-13 Thread Sean DiZazzo
On Wednesday, September 13, 2017 at 12:06:20 PM UTC-7, larry@gmail.com 
wrote:
> I have a script that creates a tmp dir, create a lot of files in it,
> and when done, does a rmtree on the dir. When it does that I get this
> message:
> 
> shell-init: error retrieving current directory: getcwd: cannot access
> parent directories: No such file or directory
> 
> But no exception is thrown. How can I determine why I get this message?

I usually see that message when I am in a directory in the shell but it has 
already been deleted by another process.  

Make sure the directory exists.  Is another part of your script deleting the 
root directory while rmtree is running?  Or something of the like.

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


traceback.format_exc() returns 'None\n'?!

2017-08-31 Thread Sean DiZazzo
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import traceback
>>> tb = traceback.format_exc()
>>> type(tb)

>>> tb
'None\n'
>>> 


Shouldn't it just return None itself?  Why a string with a newline?

Interested if there is an actual reason for this behavior or if it should be 
reported as a bug.

~Sean
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bug or intended behavior?

2017-06-03 Thread Sean DiZazzo
On Friday, June 2, 2017 at 10:46:03 AM UTC-7, bob gailer wrote:
> On 6/2/2017 1:28 PM, Jussi Piitulainen wrote:
> > sean.diza...@gmail.com writes:
> >
> >> Can someone please explain this to me?  Thanks in advance!
> >>
> >> ~Sean
> >>
> >>
> >> Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47)
> >> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> >> Type "help", "copyright", "credits" or "license" for more information.
> > print "foo %s" % 1-2
> >> Traceback (most recent call last):
> >>File "", line 1, in 
> >> TypeError: unsupported operand type(s) for -: 'str' and 'int'
> > The per cent operator has precedence over minus. Spacing is not
> > relevant. Use parentheses.
> 
> 
> In other words "foo %s" % 1 is executed, giving "1". Then "1"-2 is 
> attempted giving the error.
> Also: If there is more than one conversion specifier the right argument 
> to % must be a tuple.
> I usually write a tuple even if there is only one conversion specifier - 
> that avoids the problem
> you encountered and makes it easy to add more values when you add more 
> conversion specifiers.
> 
> print "foo %s" % (1-2,)
> 
> Bob Gailer

I get what it's doing, it just doesn't make much sense to me.  Looking at 
operator precedence, I only see the % operator in regards to modulus.  Nothing 
in regards to string formatting.  Is it just a side effect of the % being 
overloaded in strings?   Or is it intentional that it's higher precedence...and 
why?

Maybe I'm making too big a deal of it.  It just doesn't 'feel' right to me.

~Sean
-- 
https://mail.python.org/mailman/listinfo/python-list


Bug or intended behavior?

2017-06-02 Thread sean . dizazzo
Can someone please explain this to me?  Thanks in advance!

~Sean


Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print "foo %s" % 1-2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ftplib - Did the whole file get sent?

2010-10-23 Thread Sean DiZazzo
On Oct 22, 10:48 pm, Steven D'Aprano  wrote:
> On Fri, 22 Oct 2010 22:03:38 -0700, Sean DiZazzo wrote:
> > How can I assure him (and the client) that the transfer completed
> > successfully like my log shows?
>
> "It has worked well for many years, there are no reported bugs in the ftp
> code
> [...]

Thanks for your advice Steven.  I agree with you,and did take that
approach to start with.  Then the request for the actual FTP "ack"
caught me off guard.  I had to break out Wireshark and run a few tests
just to make sure I knew exactly what I was talking about.

I think I will try to explain that asking for the "ack" is not really
a valid request.  Something like this:

"Technically, these messages are used only on the lowest level of the
FTP protocol itself.  Any client or library implementing FTP would be
sending these messages under the covers...in this case I think its
done in the socket library.  It is possible that there is a bug in the
Python FTP library, just like it's possible there is a bug in any
other FTP client.  Considering how long this library has been around
(~15-20 years), and how often it is used, it is very unlikely that a
bug causing a partial transfer but showing a success has managed to
stick around for so long."

Does that make sense?

> > Is ftplib reliable enough to say that if an exception is not thrown,
> > that the file was transferred in full?
>
> Python 2.4 is pretty old. Have you checked the bug tracker to see if
> there are any reported bugs in ftplib that might be relevant? Or the
> What's New for 2.5, 2.6 and 2.7? The source code for ftplib seems fairly
> straightforward to me -- if there was an error, I can't see that it could
> have been suppressed.
>
> But really, unless you can reproduce the error, I'd say the error lies
> elsewhere.
>
> --
> Steven

I'll check bugs and whats new before sending any response.  The more I
think about this, I am beginning to think that he is just trying to
find someone to blame for a problem, and has chosen me.

Thanks again.

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


ftplib - Did the whole file get sent?

2010-10-22 Thread Sean DiZazzo
Hi,

I have some scripts that send files via ftplib to a client's ftp
site.  The scripts have generally worked great for a few years.
Recently, the client complained that only part of an important  file
made it to their server.  My boss got this complaint and brought it to
my attention.

The first thing I did was track down the specific file transfer in my
logs.  My log showed a success, I told my boss that, but he wasn't
satisfied with my response.  He began asking if there is a record of
the file transfer ack and number of bytes sent for this transfer.  I'm
not keeping a record of that...only success or failure (and some
output)

How can I assure him (and the client) that the transfer completed
successfully like my log shows?  I'm using code similar to the
following:

try:
ftp = ftplib.FTP(host)
ftp.login(user, pass)
ftp.storbinary("STOR " + destfile, open(f.path, 'rb'))
# log this as success
except:
# log this as an error

Is ftplib reliable enough to say that if an exception is not thrown,
that the file was transferred in full?

Python 2.4.3 (#1, Sep 17 2008, 16:07:08)
Red Hat Enterprise Linux Server release 5.3 (Tikanga)

Thanks for your thoughts.

~Sean

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


Re: Help with suds: HTTP Error 401

2010-06-19 Thread Sean DiZazzo
On Jun 11, 5:27 am, Eric von Horst  wrote:

> I have small program that tries to open a wsdl. When I execute the
> program I am getting 'suds.transport.TransportError: HTTP Error 401:
> Unauthorized'

Hey Eric,

Im a suds noob as well.  I found some code that led me to the below
example.  It worked for me when connecting to one particular site.  I
couldnt tell you why though...  I guess its worth a shot.

from suds.transport.https import HttpAuthenticated
import urllib2

t = HttpAuthenticated(username='me', password='password')
t.handler = urllib2.HTTPBasicAuthHandler(t.pm)
t.urlopener =  urllib2.build_opener(t.handler)
c = client.Client(url='http://xxx.xxx.xxx.xxx/path/to?
WSDL',transport=t)

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


Re: getting up arrow in terminal to scroll thought history of python commands

2010-06-13 Thread Sean DiZazzo
On Jun 13, 4:39 pm, Vincent Davis  wrote:
> On Sun, Jun 13, 2010 at 5:28 PM, Gerry Reno  wrote:
> > sounds like your keymapping got messed with.
>
> > you could just:
> > set -o vi
> > python
> > ESC, Ctrl-j
> > and now ESC-k and ESC-j will take you back and forth in history (std vi
> > editing)
>
> This is done within python? Let make sure I am clear. This is only an
> issue within the interactive python for the python dist I have built
> from source not other pythons or terminal in general. I look into the
> commands you suggested more but ESC-k and ESC-j don't sound very
> appealing to me.
>
> Thanks
> Vincent
>
>
>
> > -Gerry
>
> > Jun 13, 2010 07:22:40 PM, vinc...@vincentdavis.net wrote:
>
> > I just installed 2.6 and 3.1 from current maintenance source on Mac
> > OSx. When I am running as an interactive terminal session the up arrow
> > does not scroll thought the history of the py commands I have entered
> > I just get ^[[A. When I install from a compiled source it works fine.
> > Whats the fix for this?
>
> > Thanks
> > Vincent
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

There used to be a problem with readline support in Mac.  Not sure if
the problem still exists in Leopard/Snow Leopard.

Google for "python mac readline" and you will find some stuff.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Drilling down in a dict with "complex" objects

2010-05-24 Thread Sean DiZazzo
On May 24, 9:34 pm, Six  wrote:
> I am trying to access an objects sub-object attributes. I can boil the
> code I am working with down to this problem section:
> (snip)
> class Pt:
>   x = None
>   y = None
>   def __init__(self, x, y):
>     self.x, self.y = x, y
>   pass
>
> class Pts:
>   curr_point = None
>   next_point = None
>   def __init__(self, n, m):
>     self.next_point = Pt(n, m)
>   def update(self, point):
>     self.curr_point = self.next_point
>     self.next_point = point
>
> class PtManage:
>   points = {}
>   def __init__(self):
>     pass
>
> point = Pts(3,5)
> pman = PtManage()
> pman.points["odds"] = point
> print dir(pman)
>
> print pman["odds"].next_point.x
>
> (snip)
>
> It's this last line that doesn't work. What am I doing wrong? Is this
> a failure of the design or am I missing something obvious? How do I
> get down and see that "Pt" classes x attribute within the PtManage
> dict?

Don't you mean?

pman.points["odds"].next_point.x
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursively remove all the directories and files which begin with '.'

2010-05-16 Thread Sean DiZazzo
On May 14, 8:27 am, albert kao  wrote:
> On May 14, 11:01 am, J  wrote:
>
>
>
> > On Fri, May 14, 2010 at 10:53, albert kao  wrote:
>
> > > C:\python>rmdir.py
> > > C:\test\com.comp.hw.prod.proj.war\bin
> > > ['.svn', 'com']
> > > d .svn
> > > dotd C:\test\com.comp.hw.prod.proj.war\bin\.svn
> > > Traceback (most recent call last):
> > >  File "C:\python\rmdir.py", line 14, in 
> > >    rmtree(os.path.join(curdir, d))
> > >  File "C:\Python31\lib\shutil.py", line 235, in rmtree
> > >    onerror(os.remove, fullname, sys.exc_info())
> > >  File "C:\Python31\lib\shutil.py", line 233, in rmtree
> > >    os.remove(fullname)
> > > WindowsError: [Error 5] Access is denied: 'C:\\test\
> > > \com.comp.hw.prod.proj.war\\bin\\.svn\\entries'
>
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> > You don't have permissions to remove the subdir or file entries in the
> > .svn directory...
>
> > Maybe that file is still open, or still has a lock attached to it?
>
> I reboot my windows computer and run this script as administrator.
> Do my script has a bug?

Are the directory or files marked as read only?

See this recipe and the comment from Chad Stryker:

http://code.activestate.com/recipes/193736-clean-up-a-directory-tree/

"Although it is true you can use shutil.rmtree() in many cases, there
are some cases where it does not work. For example, files that are
marked read-only under Windows cannot be deleted by shutil.rmtree().
By importing the win32api and win32con modules from PyWin32 and adding
line like "win32api.SetFileAttributes(path,
win32con.FILE_ATTRIBUTE_NORMAL" to the rmgeneric() function, this
obstacle can be overcome."

It might not be your problem, but if it is, this had me stumped for a
few weeks before I found this comment!

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


Re: client to upload big files via https and get progress info

2010-05-13 Thread Sean DiZazzo
On May 13, 9:54 pm, Sean DiZazzo  wrote:
> On May 13, 9:39 am, News123  wrote:
>
>
>
> > Hi Aaaz,
>
> > Aahz wrote:
> > > In article <4bea6b50$0$8925$426a7...@news.free.fr>,
> > > News123   wrote:
> > >> I'd like to perform huge file uploads via https.
> > >> I'd like to make sure,
> > >> - that I can obtain upload progress info (sometimes the nw is very slow)
> > >> - that (if the file exceeds a certain size) I don't have to
> > >>  read the entire file into RAM.
>
> > > Based on my experience with this, you really need to send multiple
> > > requests (i.e. "chunking").  There are ways around this (you can look
> > > into curl's resumable uploads), but you will need to maintain state no
> > > matter what, and I think that chunking is the best/simplest.
>
> > I agree I need  chunking. (the question is just on which level of the
> > protocol)
>
> > I just don't know how to make a chunkwise file upload or what library is
> > best.
>
> > Can you recommend any libraries or do you have a link to an example?
>
> > I'd like to avoid to make separate https post requests for the chunks
> > (at least if the underlying module does NOT support keep-alive connections)
>
> > I made some tests with high level chunking (separate sequential https
> > post requests).
> > What I noticed is a rather high penalty in data throughput.
> > The reason is probably, that each request makes its own https connection
> > and that either the NW driver or the TCP/IP stack doesn't allocate
> > enough band width to my request.
>
> > Therefore I'd like to do the chunking on a 'lower' level.
> > One option would be to have a https module, which supports keep-alive,
>
> > the other would be  to have a library, which creates a http post body
> > chunk by chunk.
>
> > What do others do for huge file uploads
> > The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
>
> > N
>
> You could also just send the file in one big chunk and give yourself
> another avenue to read the size of the file on the server.  Maybe a
> webservice that you call with the name of the file that returns it's
> percent complete, or it could just return bytes on disk and you do the
> math on the client side.  Then you just forget about the transfer and
> query the file size whenever you want to know...or on a schedule.
>
> ~Sean

oops...that doesn't help with the other requirements.  My suggestion
is to not use https.  I don't think it was created to move around
large pieces of data.  Lots of small pieces rather.  SFTP?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: client to upload big files via https and get progress info

2010-05-13 Thread Sean DiZazzo
On May 13, 9:39 am, News123  wrote:
> Hi Aaaz,
>
> Aahz wrote:
> > In article <4bea6b50$0$8925$426a7...@news.free.fr>,
> > News123   wrote:
> >> I'd like to perform huge file uploads via https.
> >> I'd like to make sure,
> >> - that I can obtain upload progress info (sometimes the nw is very slow)
> >> - that (if the file exceeds a certain size) I don't have to
> >>  read the entire file into RAM.
>
> > Based on my experience with this, you really need to send multiple
> > requests (i.e. "chunking").  There are ways around this (you can look
> > into curl's resumable uploads), but you will need to maintain state no
> > matter what, and I think that chunking is the best/simplest.
>
> I agree I need  chunking. (the question is just on which level of the
> protocol)
>
> I just don't know how to make a chunkwise file upload or what library is
> best.
>
> Can you recommend any libraries or do you have a link to an example?
>
> I'd like to avoid to make separate https post requests for the chunks
> (at least if the underlying module does NOT support keep-alive connections)
>
> I made some tests with high level chunking (separate sequential https
> post requests).
> What I noticed is a rather high penalty in data throughput.
> The reason is probably, that each request makes its own https connection
> and that either the NW driver or the TCP/IP stack doesn't allocate
> enough band width to my request.
>
> Therefore I'd like to do the chunking on a 'lower' level.
> One option would be to have a https module, which supports keep-alive,
>
> the other would be  to have a library, which creates a http post body
> chunk by chunk.
>
> What do others do for huge file uploads
> The uploader might be connected via ethernet, WLAN, UMTS, EDGE, GPRS. )
>
> N

You could also just send the file in one big chunk and give yourself
another avenue to read the size of the file on the server.  Maybe a
webservice that you call with the name of the file that returns it's
percent complete, or it could just return bytes on disk and you do the
math on the client side.  Then you just forget about the transfer and
query the file size whenever you want to know...or on a schedule.

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


Re: win32wnet.WNetAddConnection2 to specific network interface?

2010-04-14 Thread Sean DiZazzo
On Apr 14, 9:22 pm, Dennis Lee Bieber  wrote:
> On Wed, 14 Apr 2010 15:18:11 -0700 (PDT), Sean DiZazzo
>  declaimed the following in
> gmane.comp.python.general:
>
>
>
> >     def wnet_connect(self, host, username, password):
>
>         The presence of "self" in that parameter list implies this is a
> method defined inside a class.
>
> >                     return wnet_connect(host, username, password)
>
>         This recursive call is missing the instance reference...
>
>                                 return self.wnet_connect(...)


Wow.  Good eye!  To be honest, I'm not sure how that happened.  I
guess it should have given me an error if it ever reached that block
though, right?

I'll take a close look at that tomorrow AM.  Thanks!

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


win32wnet.WNetAddConnection2 to specific network interface?

2010-04-14 Thread Sean DiZazzo
Hi!

I have a small app that uses pywin32 to log on to a remote host and
send some files around.  It works well, but I've found a machine that
the app won't work on.

The machine is dual-homed, with one interface able to see the server
machine, but the other can not.  I don't have the exact error because
I can't currently get on to the machine where the app fails, but I am
told it is something like that "that server doesn't exist".

Could it be that it is trying to use the wrong interface?  ie.  The
interface on the wrong vlan?  If so, is there a way to force the
connection to go to a specific interface?  I'll post the exact error
after I can get on that machine.  Thanks!

~Sean

I'm using this wnet_connect() function that I found somewhere.  It
works perfectly except on this one machine.

def wnet_connect(self, host, username, password):
unc = ''.join(['', host])
try:
win32wnet.WNetAddConnection2(win32.RESOURCETYPE_DISK,
None,
 unc,
None, username, password)
except Exception, err:
if isinstance(err, win32wnet.error):
if err[0] == 1219:
win32wnet.WNetCancelConnection2(unc, 0, 0)
return wnet_connect(host, username, password)
raise err


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


Re: getopt question

2010-04-09 Thread Sean DiZazzo
On Apr 9, 4:37 pm, Raphael Mayoraz  wrote:
> Ooops, forgot to attach the file in my first e-mail. Now, here it is.
>
> 
> Hello,
>
> I have some trouble to make getopt.getopt work and the way I want (and
> is described in the documentation).
>
> Attached is very small script to reproduce my problem.
>
> If running:
>  > python testGetOpt.py -a junk1 -b junk2
> everything is ok
>
>  > python testGetOpt.py -c junk1
> ok too: I get the 'Invalid option' error message
>
> now:
>  > python testGetOpt.py -a junk1 -c junk2
> I'm expecting this to also print the error message, as 'c' is not in the
> argument given in getopt.getopt, but it doesn't.
>
> What am I doing wrong ?
>
> Using python 2.6.4 on WindowXP.
>
> Thanks.
>
> Raphael
> -
>
> [testGetOpt.py< 1K ]#!/usr/bin/env python
> import sys
> import getopt
>
> try:
>     opts, args = getopt.getopt(sys.argv[1:], 'ab')
> except getopt.error:
>     print 'Invalid option'
>     sys.exit(0)

If your argument is expecting a value, you need to add a colon after
it in the argument string.  ie.  'a:b:'

Guessing if you print 'args' from your example, both the -c and junk1
will be in there.

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


Re: MySQLdb compiled -- Import issue

2010-03-24 Thread Sean DiZazzo

> You are right. I was trying to import the module sitting on the source
> folder :"-). Thanks for your quick response and let me try further.


Sweet!  I remember it because it confused the hell out of me on at
least one past occasion.  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb compiled -- Import issue

2010-03-24 Thread Sean DiZazzo
On Mar 24, 7:59 pm, Kurian Thayil  wrote:
> Hi All,
>
> I am just a month old with Python and trying to learn CGI with Python. I
> was trying to install MySQLdb module in my new CentOS 5.3 box with
> Python 2.4.3 default install. I downloaded the tar-ball of MySQLdb
> module (MySQL-python-1.2.3c1). Did build as normal user and install as
> root. MySQL server version that I'm using is 5.1.41, if that has
> anything to do with the error. I then copied, libmysqlclient_r.so.16
> library to /usr/lib/ folder and then I am able to import the module as
> root user. But cannot do this as normal user.
>
> Now, while doing import MySQLdb as normal user, I get the following
> error message. The scripts will be run as apache and hence cannot have
> this error. Please check the following output. Also I have attached the
> output while doing build and install process.
>
> [kuria...@server MySQL-python-1.2.3c1]$ python
> Python 2.4.3 (#1, Jan 21 2009, 01:10:13)
> [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> import MySQLdb
>
> /usr/lib/python2.4/site-packages/MySQL_python-1.2.3c1-py2.4-linux-i686.egg/_mysql.py:3:
>  UserWarning: Module _mysql was already imported from 
> /usr/lib/python2.4/site-packages/MySQL_python-1.2.3c1-py2.4-linux-i686.egg/_mysql.pyc,
>  but /opt/downloads/py-modules/MySQL-python-1.2.3c1 is being added to sys.path
>
> It would be a great help if I understand what's going on!!! Thanks in
> advance.
>
> Regards,
>
> Kurian Mathew Thayil.
>
>  MySQLdb-build.txt
> 3KViewDownload
>
>  MySQLdb-Install.txt
> 6KViewDownload
>
>  signature.asc
> < 1KViewDownload

The warning looks familiar.  Are you running python from the MySQLdb
source directory?  ie.  /opt/downloads/py-modules/MySQL-python-1.2.3c1

I think you just need to change directories and the warning will go
away.  Check what's happening on line 3 of _mysql.py  I don't have the
source in front of me.

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


Re: Updates about Tk

2010-02-27 Thread Sean DiZazzo

> Are the new Tk comaprable with other toolkits(Qt, GTK,Wx?)?
> Does Tk lack other features compared to the Qt,GTK,Wx...?
> (Or: is there things you can't simply do with Tk?)
>
> Thanks in advance for replying

tkinter is a good starting point.  You can get some definite benefits
going to wx or Qt.  I guess it depends on how much experience you have
creating GUIs.

Choose the one you are comfortable with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executable problem - correction

2010-02-24 Thread Sean DiZazzo
On Feb 24, 9:22 pm, Gib Bogle  wrote:
> The program doesn't fail with the write error on the other XP machine, it
> actually fails to execute at all, complaining about the configuration
> information.  Therefore I'm seeing different behaviour on three XP machines:
>
> Box 1 (SP2): runs OK
> Box 2 (SP3): fails to start
> Box 3 (SP3): starts up, all Qt stuff works, fails after invoking the Fortran 
> DLL
>
> Just to add to the confusion, execution is successful on a Windows 7 box.
>
> I forgot to mention that the laptop on which the program was built (and where 
> it
> runs OK) is using Vista.  I now see that it will probably be necessary to 
> build
> separate Vista and XP versions - I should have realized this earlier, but was
> misled by the fact that the Vista-built program runs OK on my XP SP2 box.

Did you compile the program with python 2.6?  Try compiling with 2.5.

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


Re: Question about getmtime

2010-02-19 Thread Sean DiZazzo
On Feb 19, 10:06 am, MRAB  wrote:
> Brandon wrote:
> > Hi everyone,
>
> > Does copying or moving a file affect the return value of
> > os.path.getmtime(path)?
>
> The modification time of a copied file should be the same as the
> original.
>
> The creation time of a copied file will be the time at which it was
> copied, so that can result in the paradoxical state of a file having
> been modified _before_ it was created! :-)

ctime does not stand for creation time.  I went through this a couple
of months ago.  It's updated whenever the inode is updated, so
changing permissions, among other things will update it.

It blew me away when I finally found this out.

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


Re: How do you implement a Progress Bar

2010-02-13 Thread Sean DiZazzo
On Feb 12, 11:33 pm, J Wolfe  wrote:
> I would really appreciate some help with this.  I'm fairly new to
> using classes...What am I doing wrong? All I get is a blank window. I
> can't seem to figure out how to initialize this Progress Bar.
>

Study and hack on this: http://uucode.com/texts/pylongopgui/pyguiapp.html

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


Re: equivalent of Ruby's Pathname?

2010-02-09 Thread Sean DiZazzo
On Feb 8, 2:36 pm, a...@pythoncraft.com (Aahz) wrote:
> In article 
> ,
> Sean DiZazzo   wrote:
>
> >On Feb 3, 6:08=A0pm, alex23  wrote:
>
> >> There was also a PEP with another possible implementation:
> >>http://www.python.org/dev/peps/pep-0355/
>
> >Why did Path() get rejected?  Is it the idea itself, or just the
> >approach that was used?  What are the complaints?
>
> You should search for the discussiona around it.
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> import antigravity

I read the discussion, and there was definitely some going back and
forth on whether it should be sub-classed from string, but the
conversation just seemed to stop abruptly with no decision one way of
the other.  Maybe I missed a thread.

I guess being dropped without a final go-ahead is just as good as a
formal no anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing Commands From Windows Service

2010-02-09 Thread Sean DiZazzo
On Feb 9, 6:52 am, T  wrote:
> On Feb 8, 2:25 pm, David Bolen  wrote:
>
>
>
> > T  writes:
> > > I have a script, which runs as a Windows service under the LocalSystem
> > > account, that I wish to have execute some commands.  Specifically, the
> > > program will call plink.exe to create a reverse SSH tunnel.  Right now
> > > I'm using subprocess.Popen to do so.  When I run it interactively via
> > > an admin account, all is well.  However, when I'm running it via
> > > service, no luck.  I'm assuming this is to do with the fact that it's
> > > trying to run under the LocalSystem account, which is failing.  What
> > > would be the best way around this?  Thanks!
>
> > The LocalSystem account is not, if I recall correctly, permitted to
> > access the network.
>
> > You'll have to install the service to run under some other account that
> > has appropriate access to the network.
>
> > -- David
>
> The more testing I do, I think you may be right..I was able to get it
> to work under a local admin account, and it worked under debug mode
> (which would also have been running as this user).  I'm a bit
> surprised though - I was under the assumption that LocalSystem had
> rights to access the network?

You really need a way to see the error you are getting.  If you can't
get it to show you the error in the shell, set up some logging to a
file, and find the error that way.  I think the user can access the
network just fine, but that maybe plink.exe is not in his path or some
such thing.

Find the error!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing Commands From Windows Service

2010-02-08 Thread Sean DiZazzo

>
> It's working fine when I run it via " debug" - that's how
> I was testing before.  It's when I start the service that it fails -
> and you can see that, when you run it with debug, plink.exe runs under
> my username.  When I run it as a service, it runs under System...

You can have the service run as any user under the service
properties.  Perhaps set the service to run under your username?

There may be some environment variables set in your session that
aren't in the one its running as.  So maybe check there as well.

Off to drink beer.  Good luck.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Executing Commands From Windows Service

2010-02-07 Thread Sean DiZazzo
On Feb 7, 4:57 pm, T  wrote:
> Thanks for the suggestions -  I think my next step is to try running
> it under an admin user account, as you guys both mentioned.  Alf -
> you're absolutely right, Microsoft has srvany.exe, which allows you to
> run any EXE as a Windows service.  I've done this in the past, but
> it's more of a "hack"..so this go around (since I will be distributing
> this program), I wanted to go the more professional route..which,
> unfortunately, involves learning the "scum". :)  I  posted this to
> comp.os.ms-windows.programmer.win32, so we'll see if what the Win32
> programmers have to say as well.  Thanks again!

I use windows services and they are very reliable.  I would say though
that relying on plink.exe is much less reliable than either python or
the service that it is running under.

Why not take a look at paramiko as the ssh client library?  I think it
runs under windows.  Also perhaps Twisted has something.  Either way
would be light years ahead of using subprocess with plink.

Just my thoughts.

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


Re: Executing Commands From Windows Service

2010-02-07 Thread Sean DiZazzo
On Feb 7, 11:02 am, T  wrote:
> I have a script, which runs as a Windows service under the LocalSystem
> account, that I wish to have execute some commands.  Specifically, the
> program will call plink.exe to create a reverse SSH tunnel.  Right now
> I'm using subprocess.Popen to do so.  When I run it interactively via
> an admin account, all is well.  However, when I'm running it via
> service, no luck.  I'm assuming this is to do with the fact that it's
> trying to run under the LocalSystem account, which is failing.  What
> would be the best way around this?  Thanks!

Try running/debugging your service from the commandline as
" debug"  That should lead you to the error.

Otherwise, we need to see a traceback and some code to be better able
to help.

~Sean

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


Re: equivalent of Ruby's Pathname?

2010-02-04 Thread Sean DiZazzo
On Feb 3, 6:08 pm, alex23  wrote:
> On Feb 4, 8:47 am, Phlip  wrote:
>
> > Yes, calling os.path.walk() and os.path.join() all the time on raw
> > strings is fun, but I seem to recall from my Ruby days a class called
> > Pathname, which presented an object that behaved like a string at
> > need, and like a filesystem path at need. path + 'folder' would
> > call .join() and insert the / correctly, for example.
>
> > What's the best equivalent in Python-land?
>
> It's no longer supported, but the 3rd party 'path' module used to be
> the go-to module for this:
>
> >>> from path import path
>
> C:\Python26\lib\site-packages\path.py:32: DeprecationWarning: the md5
> module is deprecated; use hashlib instead
>   import sys, warnings, os, fnmatch, glob, shutil, codecs, md5>>> c = 
> path('C:\\')
> >>> c.listdir()
>
> [path(u'C:\\AUTOEXEC.BAT'), path(u'C:\\boot.ini'), ...]>>> (c + 
> 'python26').listdir()
>
> [path(u'C:\\python26\\circuits.pth_disabled_for_egg'), path(u'C:\
> \python26\\DLLs'), ...]>>> (c / 'python26').listdir()
>
> [path(u'C:\\python26\\circuits.pth_disabled_for_egg'), path(u'C:\
> \python26\\DLLs'), ...]
>
> I've hand edited the results for brevity...
>
> The module could do with some TLC to bring it up to date, but warning
> aside it still seems to work fine under 2.6.
>
> (From memory, I think the original author gave up when it became clear
> it would never be integrated into the standard lib[1], which is a
> shame, I think there's scope for a pathtools addition to the lib that
> provides this level of convenience...)
>
> There was also a PEP with another possible 
> implementation:http://www.python.org/dev/peps/pep-0355/
>
> Hope this helps.

It's too bad that something like this can't be agreed to.  I used a
homegrown module like this for a couple of years in my early days with
python.  It was great, but I didn't know enough at the time to make it
really useful.

Why did Path() get rejected?  Is it the idea itself, or just the
approach that was used?  What are the complaints?

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


Re: Your beloved python features

2010-02-04 Thread Sean DiZazzo
On Feb 4, 3:03 pm, Julian  wrote:
> Hello,
>
> I've asked this question at stackoverflow a few weeks ago, and to make
> it clear: this should NOT be a copy of the stackoverflow-thread
> "hidden features of Python".
>
> I want to design a poster for an open source conference, the local
> usergroup will have a table there, and in the past years there were
> some people that came to the python-table just to ask "why should I
> use python?".
>
> For those guys would be a poster quite cool which describes the most
> popular and beloved python features.
>
> So, may you help me please? If there's a similar thread/blogpost/
> whatever, please give it to me, google couldn't.
>
> Regards
> Julian

I love list comprehensions, but am currently falling for 'with'.

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


Re: PEP 3147 - new .pyc format

2010-01-31 Thread Sean DiZazzo

> Here is a recent list of magic numbers:
>
>        Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
>        Python 2.6a1: 62161 (WITH_CLEANUP optimization)
>        Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
>        Python 2.7a0: 62181 (optimize conditional branches:
>                             introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
>        Python 2.7a0  62191 (introduce SETUP_WITH)
>        Python 2.7a0  62201 (introduce BUILD_SET)
>        Python 2.7a0  62211 (introduce MAP_ADD and SET_ADD)
>
> #define MAGIC (62211 | ((long)'\r'<<16) | ((long)'\n'<<24))
>
> Regards,
> Martin

Does "magic" really need to be used?  Why not just use the revision
number?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SimpleXMLRPCServer daemon

2010-01-29 Thread Sean DiZazzo
On Jan 29, 7:54 am, Thomas Allen  wrote:
> I have a script that runs an instance of SimpleXMLRPCServer and in
> general it works as expected. In its __del__, it is supposed to clean
> up its PID file (written on boot). I have two problems with this
> server instance: The first is that tt doesn't always clean up its PID
> file; is there a more reliable way to do this than how I am currently?
> The second is that when it does crash, I don't know about it...what
> would be sufficient as a "keep-alive" script to restart it? I suppose
> I could use something like EventMachine (already installed on my
> server) to watch the PID file if it were deleted reliably.
>
> Thomas Allen

You should check out python-daemon.  I use home grown daemons all the
time, and have only played a little with the python-daemon library,
but it is surely written well, and handles lockfiles and pidfiles.

I believe you can map a function to any signal that the daemon
receives to do any kind of cleanup etc.  Ssometimes those PID files
might be left around, but the runner included with the module (i
think) checks for stale pid files.

There's all kinds of useful stuff.

In my home grown daemons I use Adam's technique, and wrap the "while
1:" block in a try except clause.

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


Re: get error install MySQLdb on Mac OS X

2010-01-28 Thread Sean DiZazzo
On Jan 28, 12:53 pm, "PS.OHM"  wrote:
> Hello Guys
>
> I have get some error when i install MySQLdb on Mac OS X
>
> after i key command $python setup.py build
>
> rusult is
> :
> :
> error: command 'gcc-4.0' failed with exit status 1
>
> How to config this poblem?

Please show a little bit more of the error
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrap a function

2010-01-28 Thread Sean DiZazzo
On Jan 28, 12:13 pm, Joan Miller  wrote:
> On 28 ene, 19:58, John Posner  wrote:
>
>
>
> > On 1/28/2010 2:24 PM, Joan Miller wrote:
>
> > > On 28 ene, 19:16, Josh Holland  wrote:
> > >> On 2010-01-28, Joan Miller  wrote:
>
> > >>> I've to call to many functions with the format:
>
> > >> run("cmd")
>
> > >> Check the docs on os.system().
> > > No. I've a function that uses subprocess to run commands on the same
> > > shell and so substitute to bash scrips. But a script full of run
> > > ("shell_command --with --arguments") is too verbose.
>
> > I'm suspicious of your original intent. Essentially, you want to write
> > code in which a literal string, such as ...
>
> >    ls -l
>
> > ... is *not* enclosed in quotes. Why run the risk of creating confusion
> > (in other people who look at your code, in syntax-checking tools, etc.)
> > between variables and literals?
>
> Yes but to that code could be prepend a sign as '$' to be identified
> and so be parsed.
>
>
>
> > But I'm in sympathy with your desire to make the code as clean as
> > possible and to minimize the number of times you have to type a quote
> > character. My suggestions:
>
> > 1. Create a function (say, "Run") that encapsulates as much of the
> > syntax as possible: os.system(), subprocess.call(), string-splitting,
> > whatever. So an invocation would look like this:
>
> >    Run("ls -l *.txt")
>
> > (I think you've already done this step.)
>
> Yes, I made a funtion very cool to call to system commands, that works
> well with pipes and passes the variables (i.e. "LANG=C grep -e 'foo' /
> home")
>
> > 2. Find a text editor that supports keyboard macros, so that a single
> > keystroke turns this text line:
>
> >    ls -l *.txt
>
> > ... into this one:
>
> >    Run("ls -l *.txt")
>
> This is not what I'm looking for. I'm supposing that could be solved
> with a DSL or a macro library, any?

Python is not perl.

Thank God/Guido.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Terminal application with non-standard print

2010-01-25 Thread Sean DiZazzo
On Jan 24, 11:27 am, Rémi  wrote:
> Hello everyone,
>
> I would like to do a Python application that prints data to stdout, but
> not the common way. I do not want the lines to be printed after each
> other, but the old lines to be replaced with the new ones, like wget
> does it for example (when downloading a file you can see the percentage
> increasing on a same line).
>
> I looked into the curses module, but this seems adapted only to do a
> whole application, and the terminal history is not visible anymore when
> the application starts.
>
> Any ideas?
>
> Thanks,
>
> Remi

You might want to take a look at the readline module.

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


Re: deriving MySQLdb class

2010-01-21 Thread Sean DiZazzo
On Jan 21, 8:17 pm, tekion  wrote:
> Sean,
> I did a little investigation, there are other classes besides
> Connection. So, could I only set up a derived class from Connection
> and still be able to use the connection to query database and retrieve
> data?

Im not sure I understand you completely...

In theory, you could use the C API directly and subclass
_mysql.connection to get at the database.  But I think the point of
MySQLdb is that they've done all the hard work.  Why not use it?

I think the other stuff in the module is in support of the Connection
() class.  ie.  You cant get a cursor unless you already have a
connection.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deriving MySQLdb class

2010-01-21 Thread Sean DiZazzo
On Jan 21, 8:00 pm, tekion  wrote:
> Sean,
> Thanks.  This is useful.  For future reference, how do I know what
> class is in MySQLdb module?

You have to explore.  ;)

I found the MySQLdb module, and looked inside the __init__.py.  Then
looked for "connect" and followed the trail.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: deriving MySQLdb class

2010-01-21 Thread Sean DiZazzo
On Jan 21, 5:48 pm, tekion  wrote:
> All,
> I am trying to write a class which inherits from MySQLdb class.  Below
> is code snippet:
> import MySQLdb
> import sys
>
> class  msql_connect(MySQLdb):
>     def __init__(self):
>         self.host     =  "hostname"
>         self.user     = "user"
>         self.password  = "passoword"
>         self.database = "database name"
>
> I am running into below error:
>  class  msql_connect(MySQLdb):
> TypeError: Error when calling the metaclass bases
>     module.__init__() takes at most 2 arguments (3 given)
>
> Does any one have an idea why?  Thanks.

MySQLdb is the name of the module, not the class you want to
subclass.  But MySQLdb.connect() is not the class either...it's a
factory function that returns instances of the class you actually want
to subclass...connections.Connection().  The below works for me.

from MySQLdb import connections
import sys

class  mysql_connect(connections.Connection):
def __init__(self):
self.host =  "host"
self.user = "user"
self.password  = "password"
self.database = "database"
connections.Connection.__init__(self, host=self.host,
user=self.user, passwd=self.password, db=self.database)

p = mysql_connect()

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


Re: setattr() oddness

2010-01-15 Thread Sean DiZazzo
On Jan 15, 2:22 pm, Terry Reedy  wrote:
> On 1/15/2010 3:37 PM, Sean DiZazzo wrote:
>
> > Should the following be legal?
>
> >>>> class TEST(object): pass
> > ...
> >>>> t = TEST()
> >>>> setattr(t, "", "123")
> >>>> getattr(t, "")
> > '123'
>
> Different people have different opinions as to whether setattr (and
> correspondingly getattr) should be strict or permissive as to whether or
> not the 'name' string is a legal name. CPython is permissive. The
> rationale is that checking would take time and prevent possible
> legitimate use cases.
>
> CPython is actually looser than this. Try
>
> t.__dict__[1] = 2
>
> Now there is an 'attribute' whose 'name' is an int! -- and which can
> only be accessed via the same trick of delving into the internals. This
> is, however, implementation behavior that would go away if an
> implementation used string-key-only dicts to store attributes.
>
> Terry Jan Reedy

Interesting.  I can understand the "would take time" argument, but I
don't see any legitimate use case for an attribute only accessible via
getattr().  Well, at least not a pythonic use case.

Thanks for the info!

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


setattr() oddness

2010-01-15 Thread Sean DiZazzo
Should the following be legal?

>>> class TEST(object): pass
...
>>> t = TEST()
>>> setattr(t, "", "123")
>>> getattr(t, "")
'123'

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


Re: PIL how to display multiple images side by side

2010-01-08 Thread Sean DiZazzo
On Jan 8, 1:43 pm, "suresh.amritapuri" 
wrote:
> Hi,
>
> In PIL, how to display multiple images in say m rows and n colums when
> I have m*n images.
>
> suresh

Sounds like a good project to learn PIL with.

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


Re: Printing plain text with exact positioning on Windows

2010-01-06 Thread Sean DiZazzo
On Jan 5, 11:40 am, KvS  wrote:
> On Jan 5, 7:16 pm, Nobody  wrote:
>
>
>
> > On Tue, 05 Jan 2010 04:40:14 -0800, KvS wrote:
> > >> Did you mean borderless printing?
> > >> Every printer needs his margins, some more some less. Some printers have 
> > >> the
> > >> ability to do borderless printing but usualy they can do it only on 
> > >> special
> > >> or photo paper. So you can adjust the pdf as you wish, even with no 
> > >> margins,
> > >> and then try to find under printer options "borderless printing". That is
> > >> why I didn't understand :-)) it is a printer thing not pdf!
>
> > > As much as possible "borderless", yes. Of course the printer will
> > > still apply some small margin, but that's ok. A margin of say <0.5 cm.
> > > is fine. So it's not a printer thing, I accept the (physical)
> > > limitations of the printer, but I want to avoid any extra margins due
> > > to software settings.
>
> > "Hardcopy" document formats such as PostScript and PDF use positions
> > relative to the edges of the page, not the margins.
>
> Right. Still, Acrobat Reader by default scales the contents to fit on
> a page and creates some margins by doing so, no? So if my text is
> close to the left and right edges, as I want, it will get scaled and
> extra margins will occur. Avoiding this still requires me to be able
> to turn off this scaling in the printing preferences somehow
> programmatically, so it doesn't seem to make the problem easier?

Maybe you could have the user print your data on a larger sheet of
paper;one that is sure to include all of the data, and include crop
marks on the printout.  The user then cuts along the crop marks to
leave a perfectly sized, marginless page. This is how printers do
bleeds.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python 2.x and running shell command

2009-12-24 Thread Sean DiZazzo
On Dec 24, 5:34 am, tekion  wrote:
> On Dec 23, 5:22 pm, Sean DiZazzo  wrote:
>
>
>
> > On Dec 23, 1:57 pm, tekion  wrote:
>
> > > All,
> > > some of the servers I have run python 2.2, which is a drag because I
> > > can't use subprocess module.  My options that I know of is popen2
> > > module.  However, it seems it does not have io blocking
> > > capabilities.   So every time run a command I have open and close a
> > > file handle.  I have command that requires interactive interaction. I
> > > want to be be able to perform following action:
> > > fout, fin = popen2.open2(cmd) #open up interactive session
> > > fin.write(cmd2);
> > > block (input)
> > > fout.readline()
> > > block output
> > > fin.write(cmd2)
> > > and so on...
>
> > > is this possible with popen2 or do I have to use pexpect for the job?
> > > Thanks.
>
> > I've never done that with subprocess, but maybe this will 
> > help:http://www.lysator.liu.se/~astrand/popen5/
>
> > ~Sean
>
> Sean, popen5 is old name for subprocess.

Right.  Thats why I thought it would help.  You _can_ use the
subprocess module on 2.2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python 2.x and running shell command

2009-12-23 Thread Sean DiZazzo
On Dec 23, 1:57 pm, tekion  wrote:
> All,
> some of the servers I have run python 2.2, which is a drag because I
> can't use subprocess module.  My options that I know of is popen2
> module.  However, it seems it does not have io blocking
> capabilities.   So every time run a command I have open and close a
> file handle.  I have command that requires interactive interaction. I
> want to be be able to perform following action:
> fout, fin = popen2.open2(cmd) #open up interactive session
> fin.write(cmd2);
> block (input)
> fout.readline()
> block output
> fin.write(cmd2)
> and so on...
>
> is this possible with popen2 or do I have to use pexpect for the job?
> Thanks.

I've never done that with subprocess, but maybe this will help:
http://www.lysator.liu.se/~astrand/popen5/

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


Re: insert unique data in a list

2009-12-13 Thread Sean DiZazzo
On Dec 13, 8:37 am, mattia  wrote:
> How can I insert non-duplicate data in a list? I mean, is there a
> particular option in the creation of a list that permit me not to use
> something like:
> def append_unique(l, val):
>     if val not in l:
>         l.append(val)
>
> Thanks,
> Mattia

Check out the set() data type.

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


Re: daemon.DaemonContext and logging

2009-12-10 Thread Sean DiZazzo
On Dec 10, 5:37 pm, Sean DiZazzo  wrote:
> I'm finally getting around to trying out the python-daemon module and
> have hit a wall.  I'm trying to set up logging inside of the "with
> daemon.DaemonContext" block.  But when I try to use a logger inside
> the block it throws an error:

Got it!  The DaemonContext closes all open file descriptors, including
the one inside the logging handler.  I got it to work by passing the
logger's file handle in with the "preserve_files" option.

~Sean

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


daemon.DaemonContext and logging

2009-12-10 Thread Sean DiZazzo
I'm finally getting around to trying out the python-daemon module and
have hit a wall.  I'm trying to set up logging inside of the "with
daemon.DaemonContext" block.  But when I try to use a logger inside
the block it throws an error:

~~
from __future__ import with_statement

import logging
import logging.handlers
import daemon
import daemon.pidlockfile
import sys

logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s")
handler = logging.FileHandler("log.file")
logger.addHandler(handler)

pid = daemon.pidlockfile.TimeoutPIDLockFile("/var/run/daemontest.pid",
10)

with daemon.DaemonContext(pidfile=pid, gid=0, uid=0,
stdout=sys.stdout, stderr=sys.stderr):
logger.info("POO")
~~

I get the following traceback:

~~
[seans_imac:~/Downloads] halfitalian% Traceback (most recent call
last):
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py", line 753, in emit
self.flush()
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py", line 731, in flush
self.stream.flush()
IOError: [Errno 9] Bad file descriptor
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py", line 1355, in shutdown
h.close()
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py", line 784, in close
self.stream.close()
IOError: [Errno 9] Bad file descriptor
Error in sys.exitfunc:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py", line 1355, in shutdown
h.close()
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/logging/__init__.py", line 784, in close
self.stream.close()
IOError: [Errno 9] Bad file descriptor
~~~

Any advice?  Also, I left in the call to TimeoutPIDLockfile() as well,
because the library's documentation is pretty sparse, and I want to
know if I'm using it properly.

Thanks in advance.

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


Re: Reading a file that is changing and getting the new lines

2009-12-01 Thread Sean DiZazzo
On Dec 1, 3:09 pm, Ouray Viney  wrote:

> Problem:
> =
> I want to read a ASCII text file that can have data appended to it.
>
> Example scenario:  As the python script is running a user/application
> adds new entries to the end of the test case file, example, adds the
> following to the file.

>
> Question:
> =
> What is the best way to handle this type of scenario using python?

There was a thread regarding 'imitating "tail -f"' recently that you
might find useful.

The best approach IMO is this one: http://www.dabeaz.com/generators/follow.py

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


Re: extracting info from media files

2009-11-07 Thread Sean DiZazzo
MediaInfo is your best bet.  http://mediainfo.sourceforge.net/en

~Sean

On Nov 6, 11:59 pm, Michele Simionato 
wrote:
> I would like to extract some simple info from media files, such as
> size, resolution, duration, codec. What's the simplest way to do it?
> Once in a time there was pymedia but I see the latest release is of
> February 2006. The solution should work on Linux and provide support
> for a large set of video formats.

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


Re: substituting list comprehensions for map()

2009-11-02 Thread Sean DiZazzo
On Nov 2, 9:01 pm, Ben Finney  wrote:
> Anh Hai Trinh  writes:
>
> > > Yes, just about any ‘map()’ operation has a corresponding list
> > > comprehension. (Does anyone know of a counter-example, a ‘map()’
> > > operation that doesn't have a correspondingly simple list
> > > comprehension?)
>
> > Try turning this into a list comprehension:
>
> >   vectorsum = lambda *args: map(sum, zip(*args))
>
> By “this” I take you to mean “the usage of ‘map’ in this code”, since
> that's the limit of my question.
>
>     >>> vectorsum = lambda *args: [sum(items) for items in zip(*args)]
>     >>> vectorsum([1,2], [3,4], [5,6])
>     [9, 12]
>     >>> vectorsum([1,2], [3,4], [5,6], [7,8])
>     [16, 20]
>
> --
>  \       “The apparent lesson of the Inquisition is that insistence on |
>   `\         uniformity of belief is fatal to intellectual, moral, and |
> _o__)    spiritual health.” —_The Uses Of The Past_, Herbert J. Muller |
> Ben Finney

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


Re: How to avoid certain directories when using os.walk?

2009-10-30 Thread Sean DiZazzo
On Oct 29, 10:17 pm, Chris Rebert  wrote:
> On Thu, Oct 29, 2009 at 9:53 PM, Peng Yu  wrote:
> > I don't see a way to avoid walking over directories of certain names
> > with os.walk. For example, I don't want os.walk return files whose
> > path include '/backup/'. Is there a way to do so? Otherwise, maybe I
> > will have to make my own program. Thank you!
>
> Read the docs! (http://docs.python.org/library/os.html#os.walk):
>
> """
> os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
>
>     Generate the file names in a directory tree by walking the tree
> either top-down or bottom-up. For each directory in the tree rooted at
> directory top (including top itself), it yields a 3-tuple (dirpath,
> dirnames, filenames).
> [...]
>     When topdown is True, the caller can modify the dirnames list
> in-place (perhaps using del or slice assignment), and walk() will only
> recurse into the subdirectories whose names remain in dirnames; this
> can be used to prune the search, impose a specific order of visiting,
> or even to inform walk() about directories the caller creates or
> renames before it resumes walk() again.
> """
>
> They even include a specific code example of how to skip unwanted
> subdirectories.
>
> Cheers,
> Chris
> --http://blog.rebertia.com

You will run into problems however if you want to delete from a tree
while ignoring certain named directories.  Directories must be empty
before they can be deleted, so you must use "topdown=False", but to
prune a search you must use "topdown=True".  At least I think that was
the problem I had with my deletion script a while back.

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


Re: ImportError: No module named _md5 - Please help

2009-10-29 Thread Sean DiZazzo
On Oct 29, 8:49 am, wadi wadi  wrote:
> I can't alter the import statement as the error log is pointing to one
> of the installed python files 'hashlib.py'
>
> /python/2.6.2/lib/python2.6/hashlib.py
>
> and I don't have the right permissions to alter the python installation.
> Any idea?
>
> On 10/29/09, Diez B. Roggisch  wrote:
>
>
>
> > Hi,
>
> > please don't post this to comp.lang.python *and* the python mailinglist.
> > Both are synchronized, so your post shows up twice on both.
>
> >> I am trying to run a python script and got this error.
>
> import _md5
> ImportError: No module named _md5
>
> > I've never seen this import. Normally, it should be
>
> >  import md5
>
> > So you might try to alter the import statement to
>
> >  import md5 as _md5
>
> > and see if things work.
>
> > It might be of course that the author of your script provided a home-grown
> > implementation of md5 which has a different interface, and called this _md5
> > to prevent name-clashes. Then you need to modify your whole script to make
> > it work.
>
> >> Googling the problem suggested that I install the 'py25-hashlib'.
>
> >> the following does not work for me 'sudo port install py25-hashlib' ,
> >> trying to install MacPorts raised many problems.
>
> >> My question is: any idea on how to install it using yum?
> >> I am running python 2.6.2 on a centos machine.
>
> > I don't understand this - you are talking about ports which is a Mac-thing,
> > but run on centos?
>
> > However that may be, this *should* be part of core python anyway. If not,
> > you might look in yum for some python-dependency-packages, no idea how to
> > do that though (debian user here)
>
> > Diez
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> Wadienil.

You are being vague and confusing.  There is no default "_md5" python
library in the standard library.  You should be either using "import
md5" (deprecated) or "import hashlib".  Unless perhaps the code you
show is from inside one of those libraries, and there is a _md5.so
that it uses but cant find.  Not sure about that.

Did you write the code above?  Or did you find it inside another
file?  If you found it inside another file what is the file?

If you still have questions, I have another approach.  Please cover
your palm and fingers with a thick layer of black ink (making sure to
cover your entire hand).  Press your hand down firmly on a piece of
bright white paper.  Allow the ink to dry.  Finally, scan the page and
post it here.  I will attempt to read your palm to find the answer.

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


Re: popen function of os and subprocess modules

2009-10-28 Thread Sean DiZazzo
On Oct 28, 7:15 am, banu  wrote:
> On Oct 28, 3:02 pm, Jon Clements  wrote:
>
>
>
> > On 28 Oct, 13:39, banu  wrote:
>
> > > Hi,
> > > I am a novice in python. I was trying to write a simple script on
> > > Linux (python 3.0) that does the following
>
> > > #cd directory
> > > #ls -l
>
> > > I use the following code, but it doesn't work:
>
> > > import os
> > > directory = '/etc'
> > > pr = os.popen('cd %s' % directory,'w')
> > > pr.close()
> > > pr = os.popen('ls -l','w')                                      #
> > > prints the content of present folder and not '/etc'
> > > pr.close()
>
> > > Can anyone suggest me how to fix this simple script? Also what is the
> > > use of read(), readlines() and write() functions?
>
> > > Now, I also read in the online python documentation that os.popen is
> > > deprecated and no longer recommended in pyhton 3.0. Instead they ask
> > > to use subprocess.popen. I am not able to figure out how to accomplish
> > > my task with subprocess.poepn also. Can anyone suggest please?
>
> > > Regards
> > > Varun
>
> > If you're only trying to get the contents of a directory, there are
> > more suitable functions - you don't need a separate process. The popen*
> > () commands are deprecated.
>
> > Try using os.listdir() - can't remember off the top of my head if
> > that's been moved to os.path.listdir() in the 3.* series, but a read
> > of the doc's will set you straight.
>
> > Ditto for read() and write().
>
> > If you describe what you're trying to achieve, maybe we can help more.
>
> > Also, if you're using 3.0, may I suggest moving to 3.1?
>
> > hth,
>
> > Jon.
>
> Thanks for the reply Jon
> Basically I need to move into a folder and then need to execute some
> shell commands(make etc.) in that folder. I just gave 'ls' for the
> sake of an example. The real problem I am facing is, how to stay in
> the folder after popen('cd directory') finishes. It seems trivial, but
> I am not able to do it.
>
> Varun

Use subprocess.Popen() with it's "cwd" argument.  Something like:

import subprocess
p = subprocess.Popen(["ls","-l"] stdout=subprocess.PIPE, cwd="/etc")

print p.stdout.read()

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


Re: Pause a thread/ execfile()

2009-10-26 Thread Sean DiZazzo
On Oct 26, 1:25 am, Babloo  wrote:
> On Oct 26, 1:01 pm, Sean DiZazzo  wrote:
>
>
>
> > On Oct 25, 11:58 pm, Babloo  wrote:
>
> > > i have a small python application with GUI (frontend) which has
> > > various functions. I have a "RUN" button which runs python scripts in
> > > the background . It basically calls execfile() function internally
> > > which runs in a thread ,  to run the python script .
>
> > > I want to implement a "PAUSE" feature which would pause the running
> > > python script . So do that i have to either pause the thread in which
> > > execfile() runs or pause execfile itself .
>
> > > When the user presses "RUN" again then the python script should resume
> > > running .
>
> > > Any ideas how to pause the thread / pause execfile() . Any other ideas
> > > for the same would be helpful .
>
> > > Thanks
>
> > I think you can do that with a threading.event().  In the gui, create
> > a new threading.event() and pass it in to the worker thread.  Set up
> > your code in the worker so that on every iteration of "work", it
> > checks to see if the event is set.  If it finds it set, then it
> > sleeps, but keeps checking until the event is unset.  When unset
> > again, it picks up and begins work again.
>
> > In the gui, your pause button just sets and unsets the event, and the
> > worker will find out and pause at the next iteration.
>
> > Depending on what kind of work your worker thread is doing, it might
> > be tough to structure the code so the event gets checked reasonably
> > often.  Hope this helps.
>
> > ~Sean
>
> > PS.  Not sure this idea will hold up when using execfile()
>
> Hi..
> Thanks for the reply . Yes tried doing exactly what you have
> suggested . i could show you the sample code .
> But some how it doesn't work and main reason could be i am using
> execfile() in the thread .
> I was trying to set the event on the press of a button . It doesnt
> pause the thread and instead keeps on executing .
> Dont know what the problem could be ???
>
> Sample code :-
>
> $$$
> import threading
>
> class TestThread(threading.Thread):
>     """
>     A sample thread class
>     """
>
>     def __init__(self):
>         """
>         Constructor, setting initial variables
>         """
>         self._stopevent = threading.Event()
>         self._sleepperiod = 1.0
>
>         threading.Thread.__init__(self, name="TestThread")
>
>     def run(self):
>         """
>         overload of threading.thread.run()
>         main control loop
>         """
>         print "%s starts" % (self.getName(),)
>
>         count = 0
>         while not self._stopevent.isSet():
>             count += 1
>             print "loop %d" % (count,)
>             self._stopevent.wait(self._sleepperiod)
>
>         print "%s ends" % (self.getName(),)
>
>     def join(self,timeout=None):
>         """
>         Stop the thread
>         """
>         self._stopevent.set()
>         threading.Thread.join(self, timeout)
>
> if __name__ == "__main__":
>     testthread = TestThread()
>     testthread.start()
>
>     import time
>     time.sleep(10.0)
>
>     testthread.join()
>
> $

I was thinking along the lines of this.  I'll bet you can find a more
efficient way of doing it, but this demonstrates what I was thinking.

import threading, time

class TestThread(threading.Thread):
def __init__(self):
self._stopevent = threading.Event()
threading.Thread.__init__(self)


def run(self):
count = 0
while 1:
if not self._stopevent.isSet():
count += 1
print count
time.sleep(1)
else:
print "paused"
time.sleep(1)

def pause(self):
self._stopevent.set()

def play(self):
self._stopevent.clear()


if __name__ == "__main__":
th = TestThread()
th.start()

time.sleep(5)
th.pause()

time.sleep(5)
th.play()

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


Re: Pause a thread/ execfile()

2009-10-26 Thread Sean DiZazzo
On Oct 25, 11:58 pm, Babloo  wrote:
> i have a small python application with GUI (frontend) which has
> various functions. I have a "RUN" button which runs python scripts in
> the background . It basically calls execfile() function internally
> which runs in a thread ,  to run the python script .
>
> I want to implement a "PAUSE" feature which would pause the running
> python script . So do that i have to either pause the thread in which
> execfile() runs or pause execfile itself .
>
> When the user presses "RUN" again then the python script should resume
> running .
>
> Any ideas how to pause the thread / pause execfile() . Any other ideas
> for the same would be helpful .
>
> Thanks

I think you can do that with a threading.event().  In the gui, create
a new threading.event() and pass it in to the worker thread.  Set up
your code in the worker so that on every iteration of "work", it
checks to see if the event is set.  If it finds it set, then it
sleeps, but keeps checking until the event is unset.  When unset
again, it picks up and begins work again.

In the gui, your pause button just sets and unsets the event, and the
worker will find out and pause at the next iteration.

Depending on what kind of work your worker thread is doing, it might
be tough to structure the code so the event gets checked reasonably
often.  Hope this helps.

~Sean

PS.  Not sure this idea will hold up when using execfile()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftplib connection fails with multiple nics

2009-10-20 Thread Sean DiZazzo
On Oct 19, 10:23 pm, Tim Roberts  wrote:
> Sean DiZazzo  wrote:
>
> >I'm trying to connect to an ftp site from a windows machine with two
> >nics going to two different networks, but I keep getting the below
> >exception:
>
> >Traceback (most recent call last):
> >  File "ftp.pyo", line 70, in connect
> >  File "ftp.pyo", line 17, in __init__
> >  File "ftplib.pyo", line 131, in connect
> >  File "socket.pyo", line 498, in create_connection
> >gaierror: [Errno 10093] getaddrinfo failed
>
> >I think it is because of the two nics, because the code runs fine on
> >other machines.  Any ideas on how to fix this?
>
> 10093 is WSANOTINITIALISED, implying that WSAStartup has not been called.
> Are you doing this in a thread?  Are these all the same version of the
> operating system?
> --
> Tim Roberts, t...@probo.com
> Providenza & Boekelheide, Inc.

The problem was that I was including "winsock.dll" and "ws2_32.dll" in
the py2exe package.  Once I removed them, the application could
connect fine.

Thank you both for your suggestions and help.

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


Re: ftplib connection fails with multiple nics

2009-10-20 Thread Sean DiZazzo
On Oct 19, 10:23 pm, Tim Roberts  wrote:
> Sean DiZazzo  wrote:
>
> >I'm trying to connect to an ftp site from a windows machine with two
> >nics going to two different networks, but I keep getting the below
> >exception:
>
> >Traceback (most recent call last):
> >  File "ftp.pyo", line 70, in connect
> >  File "ftp.pyo", line 17, in __init__
> >  File "ftplib.pyo", line 131, in connect
> >  File "socket.pyo", line 498, in create_connection
> >gaierror: [Errno 10093] getaddrinfo failed
>
> >I think it is because of the two nics, because the code runs fine on
> >other machines.  Any ideas on how to fix this?
>
> 10093 is WSANOTINITIALISED, implying that WSAStartup has not been called.
> Are you doing this in a thread?  Are these all the same version of the
> operating system?
> --
> Tim Roberts, t...@probo.com
> Providenza & Boekelheide, Inc.

Yes.  I'm running it a thread.  It's tough to debug because the code
is wrapped up as an exe.  ie. There is no local python install to test
with.

Can you elaborate on what WSANOTINITIALZED actually means?  Where is
it called in the Python code?  Inside socket.py?  Can I force a
WSASTARTUP call in python code?

PS. Im on Windows. Thanks!

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


Re: ftplib connection fails with multiple nics

2009-10-17 Thread Sean DiZazzo
On Oct 16, 4:51 pm, Sean DiZazzo  wrote:
> Hi all,
>
> I'm trying to connect to an ftp site from a windows machine with two
> nics going to two different networks, but I keep getting the below
> exception:
>
> Traceback (most recent call last):
>   File "ftp.pyo", line 70, in connect
>   File "ftp.pyo", line 17, in __init__
>   File "ftplib.pyo", line 131, in connect
>   File "socket.pyo", line 498, in create_connection
> gaierror: [Errno 10093] getaddrinfo failed
>
> I think it is because of the two nics, because the code runs fine on
> other machines.  Any ideas on how to fix this?
>
> TIA.
>
> ~Sean

What does socket.getaddrinfo() rely on??
-- 
http://mail.python.org/mailman/listinfo/python-list


ftplib connection fails with multiple nics

2009-10-16 Thread Sean DiZazzo
Hi all,

I'm trying to connect to an ftp site from a windows machine with two
nics going to two different networks, but I keep getting the below
exception:

Traceback (most recent call last):
  File "ftp.pyo", line 70, in connect
  File "ftp.pyo", line 17, in __init__
  File "ftplib.pyo", line 131, in connect
  File "socket.pyo", line 498, in create_connection
gaierror: [Errno 10093] getaddrinfo failed

I think it is because of the two nics, because the code runs fine on
other machines.  Any ideas on how to fix this?

TIA.

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


Re: the usage of 'yield' keyword

2009-10-15 Thread Sean DiZazzo
On Oct 15, 9:48 pm, Sean DiZazzo  wrote:
> On Oct 13, 6:41 pm, Peng Yu  wrote:
>
> >http://docs.python.org/reference/simple_stmts.html#grammar-token-yiel...
>
> > The explanation of yield is not clear to me, as I don't know what a
> > generator is. I see the following example using 'yield'. Could
> > somebody explain how 'yield' works in this example? Thank you!
>
> > def brange(limit):
> >   i = 0
> >   while i < limit:
> >       yield i
> >       i += 1
>
> What do you think about that Peng?!?

Please share your thoughts, as this list is a learning experience for
everyone involved.  We can learn from your thoughts/experiences as
well.

Cheers and well being,

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


Re: the usage of 'yield' keyword

2009-10-15 Thread Sean DiZazzo
On Oct 13, 6:41 pm, Peng Yu  wrote:
> http://docs.python.org/reference/simple_stmts.html#grammar-token-yiel...
>
> The explanation of yield is not clear to me, as I don't know what a
> generator is. I see the following example using 'yield'. Could
> somebody explain how 'yield' works in this example? Thank you!
>
> def brange(limit):
>   i = 0
>   while i < limit:
>       yield i
>       i += 1

What do you think about that Peng?!?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Pipeline" Generator presentation - where?

2009-09-28 Thread Sean DiZazzo
On Sep 28, 9:12 pm, alex23  wrote:
> Sean DiZazzo  wrote:
> > I remember reading (a few times) a presentation about using generators
> > to create "pipelines"  The idea was to create very specific and small
> > generator functions, and then combine them together to get larger
> > results.  The example used was to parse log files contained in gzipped
> > log files among other things.
>
> > I'd love to read it again, but I can't find it!  Can somebody please
> > point me to it?  TIA.
>
> Hey Sean,
>
> I think you're refering to David Beazley's already-classic "Generator
> Tricks for System Programmers":http://www.dabeaz.com/generators/
>
> His "A Curious Course on Coroutines and Concurrency" is also highly
> recommended (there's a link from that page).
>
> Hope this helps.

Thanks to you both!  Thats it.  I've finally begun to use generators
more frequently in my code, and I think it's a perfect time to
actually type out the examples and absorb.

Can't wait to read the coroutines presentation as well.  It's
something I've never seen.

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


Re: How to jump out of nested 'for'-loops?

2009-09-28 Thread Sean DiZazzo
On Sep 28, 8:09 pm, Peng Yu  wrote:
> Hi,
>
> I want some command to jump out of nested loop. I'm wondering what is
> the most convenient way to do so in python.
>
> for i in range(10):
>   print "i = ", i
>   for j in range(10):
>     if i*10 + j == 50:
>       print i*10 + j
>       break # I want to jump out of the loops.
>
> Regards,
> Peng

Can you please give the people who answered your question a simple
"thank you"??

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


"Pipeline" Generator presentation - where?

2009-09-28 Thread Sean DiZazzo
I remember reading (a few times) a presentation about using generators
to create "pipelines"  The idea was to create very specific and small
generator functions, and then combine them together to get larger
results.  The example used was to parse log files contained in gzipped
log files among other things.

I'd love to read it again, but I can't find it!  Can somebody please
point me to it?  TIA.

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


Re: Catch script hangs

2009-09-27 Thread Sean DiZazzo
On Sep 27, 3:40 pm, Bakes  wrote:
> Due to an ftp server issue, my python script sometimes hangs whilst
> downloading, unable to receive any more data. Is there any way that I
> could have python check, maybe through a thread or something, whether
> it has hanged (or just, if it's still active after 10 seconds, stop
> it?). I have looked at threading but there does not seem to be a stop
> method on threading, which is a problem. Could the lower level thread
> module be a solution?
>
> I was thinking something like:
> thread:
> spawn threaded timer, if it gets to 20, close the thread
> attempt download of file
> cancel threaded timer.
> exit thread.
>
> would that work at all?

I messed around, and came up with this:


import ftplib, socket

class MyFTP(ftplib.FTP):
def storbinary(self, command, f, blocksize=8192, callback=None,
timeout=0):
"""
Override the storbinary method to make the socket.connection()
object available
outside the object, and to set the timeout of the socket
"""
self.voidcmd('TYPE I')
self.conn = self.transfercmd(command)
self.conn.settimeout(timeout)
while 1:
buf = f.read(blocksize)
if not buf:
break
self.conn.sendall(buf)
if callback: callback(buf)
self.conn.close()


ftp = MyFTP("ftp.host","user","password")


fname = "FireOnTheMountain.mov"
timeout = 1


try:
with open(fname, 'r') as fi:
#send the extra timeout arg
ftp.storbinary("STOR %s" % fname, fi, timeout=timeout)
except socket.timeout:
print "TIMED OUT!"
#if we shutdown the socket connection, it seems to properly stop
the transfer
ftp.conn.shutdown(socket.SHUT_RDWR)

ftp.quit()


I think that should at least let you set a timeout for sending each
packet that will end the connection gracefully if the timeout is
reached.  Not sure if it raises any other problems.

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


Re: Poll: Do you use csv.Sniffer?

2009-09-24 Thread Sean DiZazzo
On Sep 24, 7:26 pm, s...@pobox.com wrote:
> If you are a csv module user, I have a question for you:  Do you use the
> csv.Sniffer class?
>
>     o Yes, frequently
>     o Yes, on occasion
>     o I tried it a few times but don't use it now
>     o No, I don't need it
>     o No, never heard of it
>     o No (some other reason)
>
> If you don't use it, how do you figure out the structure of your csv files?
>
>     o I just know
>     o I stumble around in the dark trying different parameters until the csv
>       reader starts to spit out useful data
>
> If csv.Sniff was to be removed from a future version of Python, how
> difficult would it be to adapt?
>
>     o No problem
>     o No problem as long as you make it available via PyPI
>     o It would be a problem
>
> If it would be a problem for you (which would not easily be solved by adding
> it to PyPI), feel free to describe why it would be a challenge for you.  In
> fact, please feel free to add any other comments you like to your response.
>
> Private replies please.
>
> Thanks,
>
> --
> Skip Montanaro - s...@pobox.com -http://www.smontanaro.net/
>     Getting old sucks, but it beats dying young

How do I mark the boxes??

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


Re: PExpect on Windows System Using Cygwin

2009-09-24 Thread Sean DiZazzo
On Sep 24, 4:37 pm, Dave Angel  wrote:
> Kevin Holleran wrote:
> > Hello,
>
> > I downloaded and installed the pexpect module and wrote a script.  All is
> > well and good, but the script proved to be pretty useful and now I was asked
> > to run it as a scheduled task up on a server to run periodically.  I was
> > intending on simply packaging it up with Py2Exe and moving it to the server
> > that way.
>
> > However, when I went to test it, I received this error
>
> > Traceback (most recent call last):
> >   File "script.py", line 17, in 
> >     import pexpect
> >   File "lib\site-packages\pexpect.py", line 85, in 
> >     support it. Pexpect is intended for UNIX-like operating systems.""")
> > ImportError: No module named resource
>
> > A critical module was not found. Probably this operating system does not
> > support it. Pexpect is intended for UNIX-like operating systems.
>
> > So now I realize that when I was testing on my system, I run cygwin and so
> > everything worked fine
>
> > Is there a .dll that I can copy with it or anything so that it works without
> > having to install cygwin on the server that will be hosting this scheduled
> > task?
>
> > Thanks for any help.
>
> > Kevin
>
> Why not just use the subprocess module?   It's built into the Windows
> distribution, and doesn't need cygwin.
>
> DaveA

Can subprocess pass things like passwords to running processes like
pexpect can?

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


Re: Date using input

2009-09-24 Thread Sean DiZazzo
On Sep 24, 7:49 am, flebber  wrote:
> On Sep 24, 11:10 pm, flebber  wrote:
>
>
>
> > On Sep 24, 10:58 pm, Dave Angel  wrote:
>
> > > flebber.c...@gmail.com wrote:
> > > > I am using python 2.6.2, I haven't updated to 3.0 yet. No I have no
> > > > class or instructor, I am learning this myself. I have Hetlands book
> > > > "Beginning Python Novice to Professional and online documentation
> > > > books so Dive into Python, python.org etc.
>
> > > > Using the SPE editor.
>
> > > > I have currently only fully written basic psuedocode to give me a
> > > > basic framework to guide myself.
>
> > > > #Basic pseudocode
> > > > #Purpose to get raw input and calculate a score for a field of options
> > > > and return that
> > > > #score in a set in descending order.
> > > > #Multiple sets sould be written to the doc
>
> > > > #Obtain date
> > > > #Check if txt file with same date exists. If yes apphend to results to
> > > > file.
> > > > #Obtain location
> > > > #Set Dictionary
> > > > #Event number
> > > > #Obtain set size
> > > > #Prompt first entry
> > > > #First Entry Number
> > > > #First Entry Name
> > > > #Set Blocks to obtain and calculate data
> > > > #Block 1 example - Placings Block
> > > > #Obtain number of events competed in
> > > > #Obtain how many times finished first
> > > > #Ensure this value is not greater than Number of Events
> > > > #Number of Firsts divide by Events * total by 15.
> > > > #Obtain Second finishes
> > > > #Ensure this value is not greater than Number of Events
> > > > #Number of Seconds divide by Events * total by 10.
> > > > #Continue On with this
> > > > #Block 2 - Lookup coach Dict and apply value.
> > > > #Obtain Surname of Coach
> > > > #Lookup Coach File and Match Name and get value.
> > > > #Blocks continue gaining and calculating values.
> > > > #create txt file named using date
> > > > #Sum Values Block1 + Block2 etc
> > > > #Print to file event number and field with name number individual
> > > > Block totals and Sum Total
> > > > #Arranged in descending Sum Total.
> > > > #Prompt are there any more events? Yes return to start
> > > > #Apphend all additional events to same day file seperated by blank line.
>
> > > How many of these steps have you attempted actually coding?  Seems to me
> > > your first two steps are just string manipulation, and you only need to
> > > use the datetime module if you need to validate.  In other words, if the
> > > user specifies the date as 31/09/2009, you might want to later bounce
> > > back to him with a complaint that September only has 30 days.
>
> > > So the first task is to accept input in the form   ab/cd/efgh   and
> > > produce a string  efgh-cd-ab.log   which you will then create as a text
> > > file.  And if the file exists, you'll append to it instead of
> > > overwriting it.   Can you do that much?
>
> > > DaveA
>
> > Trying but haven't got it working, thats why I started to try and use
> > datetime module.
>
> Surely getting it tottally mixed up
>
> from datetime import date
> def ObtainDate(params):
>   date = raw_input("Type Date dd/mm/year: %2.0r%2.0r/%2.0r%2.0r/%4.0r
> %4.0r%4.0r%4.0r")
>  print date.datetime(year-month-day)
>  #Check if txt file with same date exists. If yes apphend to results
> to file.
> date.append(datetime
>
> and
>
> def ObtainDate(params):
>     date = raw_input("Type Date dd/mm/year: ")
>     date.format = (%4.0s%4.0s%4.0s%4.0s-%2.0s%2.0s-%2.0s)
>     print date.format

I think you are looking for datetime.strptime()

input = raw_input("Type Date dd/mm/year: ")
d = datetime.strptime(input, "%d/%m/%y")
print d

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


Re: Searching a large dictionary

2009-09-23 Thread Sean DiZazzo
On Sep 23, 4:05 pm, "Rhodri James" 
wrote:
> On Wed, 23 Sep 2009 22:52:56 +0100, mike171562  
>
>  wrote:
> > Sorry for the confusion, Simon, this is almost exactly what I need,
> > but i need to be able to search for a string in a given value of an
> > item
>
> > Here is an example of the dict I am working with
>
> > {'252': [{'code': '51679', 'date': '2009-08-01 11:35:38', 'userfield':
> > '252', 'from': '9876662881', 'to': '19877760406', 'fpld': '"Foobar"
> > <9855562881>', 'result': 'ANSW', 'sec': 131}, {'code': '51679',
> > 'date': '2009-08-01 14:33:55', 'userfield': '252', 'from':
> > '9876662881', 'to': '1980391', 'fpld': '"Foobar" <9876555881>',
> > 'result': 'ANSW', 'sec': 86}]}
>
> Ugh.  This isn't, you'll notice, either of the versions of the structure
> that you told us it was.  Let's prettyprint it for added clarity:
>
> { '252': [ { 'code': '51679',
>               'date': '2009-08-01 11:35:38',
>               'userfield': '252',
>               'from': '9876662881',
>               'to': '19877760406',
>               'fpld': '"Foobar" <9855562881>',
>               'result': 'ANSW',
>               'sec': 131
>             },
>             { 'code': '51679',
>               'date': '2009-08-01 14:33:55',
>               'userfield': '252',
>               'from': '9876662881',
>               'to': '1980391',
>               'fpld': '"Foobar" <9876555881>',
>               'result': 'ANSW',
>               'sec': 86
>             }
>           ]
>
> }
>
> A dictionary containing a single entry, whose value is a list of
> dictionaries.
>
>
>
> > 252 being the key,
>
> This vaguely implies that 252 (or rather '252') is the *only*
> key.  I hope that's not true, for it would be a silly dictionary.
>
> > I need to be able to search for a string in a given
> > item , say 777 in the 'to' field so
>
> > print wtf(dict,'to','777')
>
> > would return
>
> > {'252': [{'code': '51679', 'date': '2009-08-01 11:35:38', 'userfield':
> > '252', 'from': '9876662881', 'to': '19877760406', 'fpld': '"Foobar"
> > <9855562881>', 'result': 'ANSW', 'billsec': 131}, {'code': '51679',
> > 'date': '2009-08-01 14:33:55', 'userfield': '252', 'from':
> > '9876662881', 'to': '1980391', 'fpld': '"Foobar" <9876555881>',
> > 'result': 'ANSW', 'billsec': 86}]}
>
> Which would be the entire original structure, except for some reason
> relabelling 'sec' as 'billsec' telling us very little really.
>
>
>
> > I hope this makes sense, sorry for not being clear
>
> Not a lot, frankly.  There are still a lot of unanswered questions here.
> Would I be right in thinking that you want to check all keys of the outer
> dictionary, and you want the corresponding values in the returned
> dictionary to be lists of all inner dictionaries that match?  And that
> the business with sec/billsec is a typo?
>
> Assuming that, try this:
>
> # Untested, and it is midnight
> def wtf(data_dict, key, value):
>    # Don't call it 'dict', by the way, you'll mask the builtin object
>    result = {}
>    for outer_key, data_list in data_dict.items():
>      new_list = []
>      for inner_data in data_list:
>        if value in inner_data[key]:
>          new_list.append(inner_data)
>      if new_list:
>        result[outer_key] = new_list
>    return result
>
> Note that this won't work on the 'sec' field, since it's a number rather
> than a string.
>
> --
> Rhodri James *-* Wildebeest Herder to the Masses

I like to perform what I call "objectify" on nested dictionary type
stuff into classes.

class TestPart(object):
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)


class Test(object):
def __init__(self):
self.name = None
self.entries = []

def set(self, name, listofdicts):
self.name = name
for l in listofdicts:
self.entries.append(TestPart(**l))

def search(self, key, value):
rets = []
for t in self.entries:
if value in getattr(t, key):
rets.append(t)
return rets

if __name__ == "__main__":
d = {'252': [{'code': '51679', 'date': '2009-08-01 11:35:38',
'userfield':
'252', 'from': '9876662881', 'to': '19877760406',
'fpld': '"Foobar" <9855562881>', 'result': 'ANSW', 'sec':
131}, {'code': '51679',
'date': '2009-08-01 14:33:55', 'userfield': '252',
'from':
'9876662881', 'to': '1980391', 'fpld': '"Foobar"
<9876555881>',
'result': 'ANSW', 'sec': 86}]}
items = []
for k, v in d.items():
t = Test()
t.set(k, v)
items.append(t)

for i in items:
got =  i.search("code", "9")
print got
for r in got:
print r.code

It's not quite right, but you get the basic idea.  I just find it
easier to wrap my head around structures built like this rather than
trying to remember alot of inner/outer, index variables, etc.

~Sean
-- 
http://mail.pytho

Re: Open file on remote linux server

2009-09-23 Thread Sean DiZazzo
On Sep 23, 12:04 pm, The Bear  wrote:
> Hi I'm looking to do something like this
>
> f = f.openfileobj(remotefileloc, localfilelikeobj)
>
> my remote files are on a solaris box that i can access using ssh (could
> prehap request othe protocols if necessary)
>
> anyone got any ideas?
>
> many thanks
>
> Charlie
>
> (ps. tried this on the python-forum but didn't seem to go on so apologies if
> i'm cross posting)
> --
> View this message in 
> context:http://www.nabble.com/Open-file-on-remote-linux-server-tp25531253p255...
> Sent from the Python - python-list mailing list archive at Nabble.com.

I don't know of any Python library that will give you that kind of
access to a remote file over ssh.  It sounds like a fun project
though!

If nothing else, you can install the ssh filesystem for Fuse, and just
mount the remote filesystem as if it was local.

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


Re: custom data warehouse in python vs. out-of-the-box ETL tool

2009-09-22 Thread Sean DiZazzo
On Sep 22, 1:00 pm, snfctech  wrote:
> Does anyone have experience building a data warehouse in python?  Any
> thoughts on custom vs using an out-of-the-box product like Talend or
> Informatica?
>
> I have an integrated system Dashboard project that I was going to
> build using cross-vendor joins on existing DBs, but I keep hearing
> that a data warehouse is the way to go.  e.g. I want to create orders
> and order_items with relations to members (MS Access DB), products
> (flat file) and employees (MySQL).
>
> Thanks in advance for any tips.

I have done some small/medium sized stuff using SQLAlchemy,
Turbogears, and Flex.  I have never used a commercial product, but I
imagine getting it set up to work with your data is the hardest part
of the job anyway, and the solution you end up with will most likely
limit you to applying their api to your data.  If you build it
yourself, you have complete control, and know exactly where to go when
you have a problem, or to add a feature.

I'm no expert, but I think I would try to find a way to consolidate
the data into one data source.  We handle the giant amount of data we
are collecting by preprocessing it into another DB anyway, so I
imagine you could do both things at the same time.

This could very probably be handled in a different way if you are a
DBA.  I'm just a MySQL hack.  :)

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


Re: How can I tell if variable is defined

2009-09-22 Thread Sean DiZazzo
On Sep 22, 11:03 am, "Brown, Rodrick "  wrote:
> How could I do the following check in Python
>
> In Perl I could do something like if ((defined($a)) { ... }
>
> I tried if var is not None:
> However this doesn't seem to work as described.
>
> Thanks.

try:
var
except NameError:
handle_it()

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


Re: using python 2.5

2009-09-21 Thread Sean DiZazzo
On Sep 21, 4:42 pm, "kunal.k"  wrote:
> I have installed python 2.5 for a particular code. Now i have 2.6
> already installed. How do i direct this code to use the 2.5 modules??

I don't think you do.  You should install the modules for python 2.6.
You could try to hand copy the modules, and some might work, but it's
crap shoot.

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


Re: easy question, how to double a variable

2009-09-21 Thread Sean DiZazzo
On Sep 21, 1:46 pm, daggerdvm  wrote:
> u don't want to answerthen why post?...get lost.

I eat children...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: control CPU usage

2009-09-19 Thread Sean DiZazzo
On Sep 19, 9:17 am, kakarukeys  wrote:
> Hi,
>
> When I am running a loop for a long time, calculating heavily, the CPU
> usage
> is at 100%, making the comp not so responsive. Is there a way to
> control the
> CPU usage at say 80%? putting a time.sleep(0.x) doesn't seem to help
> although CPU usage level is reduced, but it's unstable.
>
> Regards,
> W.J.F.

If you are on linux, you can use the 'nice' command.  It will still
take 100%, but will give it up to other processes that need to use the
cpu.

nice -n 19 

Re: Granularity of OSError

2009-09-18 Thread Sean DiZazzo
On Sep 18, 5:23 pm, Christian Heimes  wrote:
> kj wrote:
> > For example, LBYL would look like this:
>
> > if os.path.isfile(some_file):
> >     os.unlink(some_file)
>
> > In contrast, EAFP would look like this:
>
> > try:
> >     os.unlink(some_file)
> > except OSError:
> >     pass
>
> The two version aren't equal. The first one suffers from a race
> condition which may lead to a severe security issue. The file may be
> gone or replaced by a different file in the time span between the check
> and the call to unlink().
>
> Christian

Thanks for pointing that out.  I never thought of it before.

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


Re: Creating a local variable scope.

2009-09-18 Thread Sean DiZazzo
On Sep 11, 10:36 am, Johan Grönqvist 
wrote:
> Hi All,
>
> I find several places in my code where I would like to have a variable
> scope that is smaller than the enclosing function/class/module definition.
>
> One representative example would look like:
>
> --
> spam = { ... }
> eggs = { ... }
>
> ham = (a[eggs], b[spam])
> --
>
> The essence is that for readability, I want spam and eggs in separate
> definitions, but for clarity, I would like to express the fact that they
> are "local to the definition of ham", i.e., they are not used outside of
>   the definition of ham.
>
> The language reference at
>  says that "The
> following are blocks: a module, a function body, and a class
> definition." (all other cases seem to refer to dynamic execution using
> eval() or similar). Python 3 and 2.6 seem to have identical scope rules.
>
> In the other languages I have used I can either use braces (C and
> descendants) or use let-bindings (SML, Haskell etc.) to form local scopes.
>
> Are there suggestions or conventions to maximize readability for these
> cases in python? (Execution time is not important in the cases I
> currently consider.)
>
> Regards
>
> Johan

I would do something like this:

>>> class Namespace(object):
... pass
...
>>> n = Namespace()
>>> n.f = 2
>>> n.g = 4
>>> print f
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'f' is not defined
>>> print n.f
2

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


Re: Why use "locals()"

2009-09-18 Thread Sean DiZazzo
On Sep 18, 9:55 am, Simon Forman  wrote:
> On Mon, Sep 14, 2009 at 1:12 AM, Sean DiZazzo  wrote:
>
> > Thanks for your explanation Steven.  I see how it can be valuable, but
> > it seems to always break the second rule of Zen.  I don't really want
> > to get into the code of debuggers, but I guess I can see how they
> > might have no other way to know what local variables have been set.
>
> > ~Sean
>
> The zeroth "rule" of zen is "don't take the rules so seriously".
> "They're really more like guidelines anyway."
>
> Regards,
> ~simon

Yeah.  I think I was just a bit randy at that moment.  I realized that
the (*args,**kwargs) idiom is very similar and I use it all the
time.

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


Re: Granularity of OSError

2009-09-18 Thread Sean DiZazzo
On Sep 18, 11:54 am, kj  wrote:
> I've often come across the idea that good Python style deals with
> potential errors using an EAFP ("easier to ask forgiveness than
> permission") strategy rather than a LBYL ("look before you leap")
> strategy.
>
> For example, LBYL would look like this:
>
> if os.path.isfile(some_file):
>     os.unlink(some_file)
>
> In contrast, EAFP would look like this:
>
> try:
>     os.unlink(some_file)
> except OSError:
>     pass
>
> But, as written, the EAFP code above is not satisfactory, because
> there can be OSError's triggered for reasons other than the
> non-existence of the regular file some_file.
>
> What one needs is a finer granularity of exception, mapping to
> exactly the error that one is guarding against.
>
> Is there a standard approach to refining the granularity of exceptions
> such as OSError?  The only approach I can think of is to somehow
> parse the error string (assuming is available) to determine whether
> the exception is indeed of the specific kind we're trying to catch.
> But this strikes me as grossly inelegant.  Is there a better way?
>
> (BTW, the problem is generic, because client code has no control
> over the specificity of the exceptions raised by a library module.
> If these exceptions turn out to be too broad, client code has to
> somehow deal with this reality, at least in the short term.)
>
> TIA!
>
> kynn

You can access the exception object which gives you greater detail.

try:
os.unlink(some_file)
except OSError, e:
print e.errno
print e.strerror

if e.errno == 2:
pass
else:
raise


If it's the error you are looking for, handle it, or else raise.

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


Re: overrideredirect vs. text entry etc. widget

2009-09-16 Thread Sean DiZazzo
On Sep 15, 10:20 pm, kernus  wrote:
> On Sep 15, 11:42 am, Sean DiZazzo  wrote:
>
>
>
> > Whats interesting is that if you call overrideredirect from a button
> > command, it works as expected.  Well, at least the text entry field
>
> ^so, Sean, you know how to *click this magic button in
> the programming way*?
>

Did you try it?  Did it work?

I tried, using button.invoke(), and a few less obvious ways
(self.tk.call()...), but couldn't do it programatically.  I don't
understand why manually clicking the button in the gui is any
different than calling it's function, or calling invoke().  I'd be
interested to know.

I also tried calling it from a different thread, or giving the gui
some time to initialize before calling it.  No love.  Only manually
clicking it seems to work.

I also found some documentation that clearly states "overrideredirect
might not work on some platforms."  So I guess I have one of those
platforms!

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


Re: overrideredirect vs. text entry etc. widget

2009-09-15 Thread Sean DiZazzo
On Sep 14, 10:43 pm, kernus  wrote:
> I just googled this post:
>
> http://mail.python.org/pipermail/python-list/2006-September/575832.html
>
> something like:
>
> from Tkinter import *
>
> root = Tk()
> Entry(root).pack()
> Button(root, text='Quit', command=sys.exit).pack()
> root.overrideredirect(1)
> root.mainloop()
>
> the button works boths under linux(debian) and windows, but the entry
> widget only works on windows, any idea?
>
> I am making a skinnalbe music player, so the issue must be solved.

Whats interesting is that if you call overrideredirect from a button
command, it works as expected.  Well, at least the text entry field
behaves for me on Ubuntu...

from Tkinter import *

root = Tk()

def override():
if root.overrideredirect():
root.overrideredirect(False)
else:
root.overrideredirect(True)

root.withdraw()
root.deiconify()

Entry(root).pack()
Button(root, text='Override', command=override).pack()
root.mainloop()

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


Re: Why use "locals()"

2009-09-13 Thread Sean DiZazzo
> If you are willing to open your mind to the possibility that some
> Pythonic things don't adhere to every Zen, then I would suggest that
> Gabrielle's examples are perfectly Pythonic shortcuts.  But if you
> don't want to use them, you don't have to, nobody is forcing you.

It's a pretty small domain, but I see the use (and the Pythonicity).

Thanks all for your advice.

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


Re: Why use "locals()"

2009-09-13 Thread Sean DiZazzo
On Sep 13, 9:11 pm, Steven D'Aprano
 wrote:
> On Sun, 13 Sep 2009 20:26:06 -0700, Sean DiZazzo wrote:
> > On Sep 13, 8:18 pm, Steven D'Aprano
> >  wrote:
> >> On Sun, 13 Sep 2009 20:06:51 -0700, Sean DiZazzo wrote:
> >> > I have never used a call to "locals()" in my code.  Can you show me a
> >> > use case where it is valuable and Pythonic?
>
> >> grep is your friend:
>
> >> $ grep "locals()" /usr/lib/python2.5/*.py
> >> /usr/lib/python2.5/decimal.py:        for name, val in
> >> locals().items(): /usr/lib/python2.5/doctest.py:        return
> >> __import__(module, globals(), locals(), ["*"])
> >> /usr/lib/python2.5/profile.py:        p.runctx('f(m)', globals(),
> >> locals()) /usr/lib/python2.5/pydoc.py:            docloc = ' >> href="%(docloc)s">Module Docs' % locals()
> >> /usr/lib/python2.5/smtpd.py:        mod =
> >> __import__(classname[:lastdot], globals(), locals(), [""])
>
> >> --
> >> Steven
>
> > That is not a use case. I still don't understand!
>
> Look at the source code to find out what they're doing with the
> information they extract from locals(), and why.
>
> For instance, profile should be obvious -- debuggers and profilers often
> need to see the values of local names.
>
> pydoc is using the fairly common idiom of injecting the values of
> variables into a string. Personally, I don't see why it uses this idiom:
>
>     docloc = 'something'
>     docloc = '%(docloc)s' % locals()
>
> instead of this:
>
>     docloc = 'something'
>     docloc = '%s' % docloc
>
> but for more complicated cases, the first idiom is much simpler.
>
> decimal seems to be using locals() to avoid this anti-pattern:
>
> def __init__(self, a, b, c, d, e, f, g, h):
>     self.a = a
>     self.b = b
>     self.c = c
>     self.d = d
>     # blah blah blah
>     self.h = h
>
> and replacing it with:
>
> def __init__(self, a, b, c, d, e, f, g, h):
>     for name, val in locals().items():
>         setattr(self, name, val)
>     del self.self
>
> Another use-case: if you have a tool that documents Python code
> automatically, it needs a way to automatically view the values of local
> names.
>
> > PS.  I know how to use grep.
>
> I'm sure you do. But you didn't think of using grep, which is why I made
> the suggestion that grepping the standard library is a good tool to use
> to search for Pythonic examples of code.
>
> It's not foolproof, e.g. the unittest module is more Java-onic than
> Pythonic, but it's a good start.
>
> --
> Steven

Thanks for your explanation Steven.  I see how it can be valuable, but
it seems to always break the second rule of Zen.  I don't really want
to get into the code of debuggers, but I guess I can see how they
might have no other way to know what local variables have been set.

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


Re: Why use "locals()"

2009-09-13 Thread Sean DiZazzo
> > I have never used a call to "locals()" in my code.  Can you show me a
> > use case where it is valuable and Pythonic?
>
> def print_item(item):
>      description = textwrap.fill(item.description, 40)
>      short = item.description.split('\n', 1)[0]
>      code = str(item.id).zfill(6)
>      print "%(code)s %(short)s\n%(description)s\n" % locals()

I see the use of that, but according to Zen, "Explicit is better than
implicit."

>
> Transferring arguments:
>
> def foo(some, long, list, of, arguments):
>      additional = 5
>      return other(**locals())
>

Why not?:

def foo(**kwargs):
kwargs["additional"] = 5
return other(**kwargs)

> Defining properties:
>
> class ColourThing(object):
>     �...@apply
>      def rgb():
>          def fset(self, rgb):
>              self.r, self.g, self.b = rgb
>          def fget(self):
>              return (self.r, self.g, self.b)
>          return property(**locals())
>

So really it's just a short hand.  But it's against the Zen! Explicit
not Implicit!  I'm not convincedthen again, I didn't look at the
source code of the standard libraries.

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


Re: Why use "locals()"

2009-09-13 Thread Sean DiZazzo
On Sep 13, 8:18 pm, Steven D'Aprano
 wrote:
> On Sun, 13 Sep 2009 20:06:51 -0700, Sean DiZazzo wrote:
> > I have never used a call to "locals()" in my code.  Can you show me a
> > use case where it is valuable and Pythonic?
>
> grep is your friend:
>
> $ grep "locals()" /usr/lib/python2.5/*.py
> /usr/lib/python2.5/decimal.py:        for name, val in locals().items():
> /usr/lib/python2.5/doctest.py:        return __import__(module, globals(), 
> locals(), ["*"])
> /usr/lib/python2.5/profile.py:        p.runctx('f(m)', globals(), locals())
> /usr/lib/python2.5/pydoc.py:            docloc = ' href="%(docloc)s">Module Docs' % locals()
> /usr/lib/python2.5/smtpd.py:        mod = __import__(classname[:lastdot], 
> globals(), locals(), [""])
>
> --
> Steven

That is not a use case.  I still don't understand!

PS.  I know how to use grep.

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


Why use "locals()"

2009-09-13 Thread Sean DiZazzo
I have never used a call to "locals()" in my code.  Can you show me a
use case where it is valuable and Pythonic?

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


Re: NameError: name '__main__' is not defined

2009-09-13 Thread Sean DiZazzo
On Sep 13, 6:43 pm, Peng Yu  wrote:
> Hi,
>
> I try the following code. I don't quite understand why __main__ is not
> defined. Could somebody let me know what I am wrong about it?
>
> Regards,
> Peng
>
> $ cat test.py
> #!/usr/bin/env python
>
> if __main__ == '__main__' :
>   print "Hello World!\n"
> $ ./test.py
> Traceback (most recent call last):
>   File "./test.py", line 3, in 
>     if __main__ == '__main__' :
> NameError: name '__main__' is not defined

erI was just angry.  __main__ doesn't exist because it is not in
your programs scope.

you are looking for:

if __name__ == "__main__":
print "Hello World"

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


Re: NameError: name '__main__' is not defined

2009-09-13 Thread Sean DiZazzo
On Sep 13, 6:43 pm, Peng Yu  wrote:
> Hi,
>
> I try the following code. I don't quite understand why __main__ is not
> defined. Could somebody let me know what I am wrong about it?
>
> Regards,
> Peng
>
> $ cat test.py
> #!/usr/bin/env python
>
> if __main__ == '__main__' :
>   print "Hello World!\n"
> $ ./test.py
> Traceback (most recent call last):
>   File "./test.py", line 3, in 
>     if __main__ == '__main__' :
> NameError: name '__main__' is not defined

Is this a production program that you are using??

Please show us the point you are trying to make in something more
valuable.

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


Re: run exe on different computer

2009-09-13 Thread Sean DiZazzo
On Sep 13, 4:57 pm, Dave Angel  wrote:
> daved170 wrote:
> > On Sep 13, 2:17 pm, Dave Angel  wrote:
>
> >> daved170 wrote:
>
> >>> Hi everybody,
> >>> I'm building a small python program that run a service (exe file) on
> >>> my servers.
> >>> I don't want to use remote desktop and it's siblings.
>
> >>> I would like to have some information on how to run an exe on a
> >>> different computer and if there a way to check if that exe is still
> >>> alive.
>
> >>> Thanks
> >>> Dave
>
> >> On a question like this, you really need to supply much more information
> >> on your constraints.  You could start by saying these servers are
> >> running Windows Server 2003.  And that they're on a domain (rather than
> >> a workgroup).  And that you're trying to access them from another
> >> machine within the same local domain, not over the internet.  And that
> >> your local machine is on the same domain, and has an account with admin
> >> privileges for all the desired servers.  And that you are allowed to do
> >> a one-time install (of something) on each server prior to this
> >> particular need.  And that each server already has Python version 2.5
> >> installed, and the IT department won't allow you to install any later
> >> version.
>
> >> Then once you have an environment, you need to specify just what kind of
> >> program you want to run on those servers.  Is it an EXE program?  Or is
> >> it Python, with a particular script?  Does it really need to be a
> >> *service*, which has a particular set of constraints, and should be
> >> installed, and started/stopped using the service manager.  Do you want
> >> this program to restart whenever the servers are restarted?
>
> >> One solution that should work for nearly every Windows topology might be
> >> to go to each server, run the scheduler task, and specify a new batch
> >> file to be run upon boot.  This batch file can check a specified
> >> (shared) directory for a python script, and if found, run it.  If not
> >> found, sleep for 60 seconds or so, then repeat.  Note that it's a good
> >> idea to put a five minute delay at the very beginning, in case the
> >> script needs to be deleted at the next boot.  Sometimes a bug requires
> >> surgery, and it's good to have enough time to do it.
>
> >> Now, to control those servers from another machine, copy an appropriate
> >> script into the prearranged directory.  Within a minute, it'll be
> >> running, and it can post whatever results it likes in another accessible
> >> directory.
>
> >> Whether this is a "safe" thing to do is a separate question.  Generally
> >> an IT department likes to have some control over just what programs run
> >> on their servers, and for good reason.
>
> >> DaveA
>
> > Hi DaveA
> > Thanks for your answer. I'll try to clearify myself.
> > For now I'm trying to do that on client & server that are win XP. They
> > both on the same domain (maybe in the future they'll be runinig on the
> > web). I have admin user on both my computers.
> > I have both an exe and a python app that I'd like to control from my
> > client.
> > Insted of logging to my Server I would like to write a python app at
> > my client that allows me to control both that exe and my Server-python-
> > app. I don't want to use the schedualer because I would like to
> > control it from my client.
> > I can install whatever I'll like on both of the computers. they are
> > mine and I have full access for them.
> > I hope I clearify myself and if there are more solutions I'll be happy
> > to be noted.
> > Thans
> > DaveD :)
>
> If you only have those two machines, you aren't on a NT domain, you've
> got a workgroup.  A Windows domain is hosted by a server OS, and XP can
> only be a client on a domain.  Without being on an NT domain, security
> is much sloppier.  In some ways that makes things easier, but you may
> hit a brick wall if you need more than one kind of simultaneous access
> to another machine.
>
> Is this EXE file you want to run on the server something out of your
> control, or could you customize that as well?  Because if you can, then
> the distinction between that and your server-python program is probably
> unimportant.  Call the programs you might want to run:   X1, X2, X3.
>
> In order to run X1 on that server without opening a console (or remote
> desktop, or whatever) on it, you will have to have something else
> already running which is willing to be a proxy on your behalf.  You then
> communicate with that program to tell it what to run, and when.  I
> suggested a batch file for that program, call it S.  It could just as
> easily have been a python script, but there's no advantage that I can
> see.  The idea is to make sure that S is always running (which is why
> you put it into the scheduler;  it'll be restarted whenever the machine
> is booted).
>
> Anyway, the idea is that S is a very lightweight program, and it can
> launch any possible Xn.  And the only question is how you want the
> client to talk to S.  If

Re: Why indentation is use to denote block of code?

2009-09-13 Thread Sean DiZazzo
On Sep 13, 3:12 pm, Peng Yu  wrote:
> Hi,
>
> I want to understand why python use indentation to denote block of
> code. What are the advantages of it? Is there a style in python to
> denote a block of code the same as that of C++ (with '{}')?
>
> One disadvantage of using indentation to denote a block of code is
> that the runtime to automatically indent a python code would be about
> a few times more than the runtime to automatically indent a C++ code
> of the same length (both are in vim).
>
> Regards,
> Peng

Looking at your other post regarding "strict mode", I have to
comment.  I think you are looking for a different language.  What you
are hoping to change about the language are some of the major things
that make it a joy to program for me.  Braces, static typing, no
indentation... What's next?  Would you like semicolons?

I suggest you spend some time just programming it the way it was made
to be programmed, and quit trying to turn it into Perl or any other
language.  If after a week or two, you don't like it, then move on.
And save us the complaints.

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


Re: Why indentation is use to denote block of code?

2009-09-13 Thread Sean DiZazzo
On Sep 13, 3:12 pm, Peng Yu  wrote:
> Hi,
>
> I want to understand why python use indentation to denote block of
> code. What are the advantages of it? Is there a style in python to
> denote a block of code the same as that of C++ (with '{}')?
>
> One disadvantage of using indentation to denote a block of code is
> that the runtime to automatically indent a python code would be about
> a few times more than the runtime to automatically indent a C++ code
> of the same length (both are in vim).
>
> Regards,
> Peng

Try this:

from __future__ import braces

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


  1   2   >