Re: using text file to get ip address from hostname

2012-09-19 Thread Dan Katorza
בתאריך יום ראשון, 16 בספטמבר 2012 01:43:31 UTC+3, מאת Dan Katorza:
> בתאריך יום רביעי, 12 בספטמבר 2012 17:24:50 UTC+3, מאת Dan Katorza:
> 
> > hello ,
> 
> > 
> 
> > 
> 
> > 
> 
> > i'm new to Python and i searched the web and could not find an answer for 
> > my issue.
> 
> > 
> 
> > 
> 
> > 
> 
> > i need to get an ip address from list of hostnames which are in a textfile.
> 
> > 
> 
> > 
> 
> > 
> 
> > this is what i have so far 
> 
> > 
> 
> > --
> 
> > 
> 
> > #!/usr/bin/env python
> 
> > 
> 
> > #Get the IP Address
> 
> > 
> 
> > 
> 
> > 
> 
> > import socket
> 
> > 
> 
> > hostname = 'need it to read from a text file'
> 
> > 
> 
> > addr = socket.gethostbyname(hostname)
> 
> > 
> 
> > print 'The address of ', hostname, 'is', addr 
> 
> > 
> 
> > 
> 
> > 
> 
> > ---
> 
> > 
> 
> > 
> 
> > 
> 
> > any idea ? 
> 
> > 
> 
> > sorry for my english
> 
> > 
> 
> > 
> 
> > 
> 
> > thanks.
> 
> 
> 
> Hi Hans,
> 
> thank you very much for the tips.
> 
> as i mentioned before I'm new to python and I'm trying to learn it step by 
> step.
> 
> thank you for showing me other ways, i will explore them.

Hello again,
I have another question and i hope you will understand me..
Is there any option where you can set the program to go back to lets say the 
top of the code?
I mean if the program finished the operation and i want to stay in the program 
and go back ro the start.
after any operation i want the option to do it again , go back to the main menu 
or full exit from the program, and i want it every time.

i hope i'm clear :)


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


Re: 'indent'ing Python in windows bat

2012-09-19 Thread Hans Mulder
On 18/09/12 05:01:14, Ian Kelly wrote:
> On Mon, Sep 17, 2012 at 7:08 PM, David Smith  wrote:
>> How do I "indent" if I have something like:
>> if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
>> sys.exit(3)
> 
> How about:
> 
> if sR == 'Cope':
> sys.exit(1)
> elif sR == 'Perform':
> sys.exit(2)
> else:
> sys.exit(3)
> 
> I don't really understand why you're trying to keep it all on one line.

He's using Windows.

If he were on Unix, there'd be no problem:

python -c 'import sys
if sR == "Cope":
sys.exit(1)
elif sR == "Perform":
sys.exit(2)
else:
sys.exit(3) '

Unfortunately, the Windows shell doesn't do multi-line strings,
so he has to cram it all on one line.


-- HansM


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


Re: using text file to get ip address from hostname

2012-09-19 Thread Chris Angelico
On Wed, Sep 19, 2012 at 5:41 PM, Dan Katorza  wrote:
>
> Hello again,
> I have another question and i hope you will understand me..
> Is there any option where you can set the program to go back to lets say the 
> top of the code?
> I mean if the program finished the operation and i want to stay in the 
> program and go back ro the start.
> after any operation i want the option to do it again , go back to the main 
> menu or full exit from the program, and i want it every time.
>
> i hope i'm clear :)

Yep! Look up the docs and tutorial on "control flow" and "looping
constructs". Sounds like what you want here is a 'while' loop.

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


Re: using text file to get ip address from hostname

2012-09-19 Thread Dan Katorza
בתאריך יום רביעי, 19 בספטמבר 2012 11:14:29 UTC+3, מאת Chris Angelico:
> On Wed, Sep 19, 2012 at 5:41 PM, Dan Katorza  wrote:
> 
> >
> 
> > Hello again,
> 
> > I have another question and i hope you will understand me..
> 
> > Is there any option where you can set the program to go back to lets say 
> > the top of the code?
> 
> > I mean if the program finished the operation and i want to stay in the 
> > program and go back ro the start.
> 
> > after any operation i want the option to do it again , go back to the main 
> > menu or full exit from the program, and i want it every time.
> 
> >
> 
> > i hope i'm clear :)
> 
> 
> 
> Yep! Look up the docs and tutorial on "control flow" and "looping
> 
> constructs". Sounds like what you want here is a 'while' loop.
> 
> 
> 
> ChrisA

Hi Chris,
this is my code:

#!/usr/bin/env python
#Get the IP Address

import sys, socket

print ("\n\n#")
print ("#Get IP from Host v 1.0 #")
print ("#")
print ("# Choose from the options below #")
print ("#  1- url , 2-File(Text file only.txt)  #")
print ("#\n")

mchoice = int(raw_input("Please enter your choice> "))
while mchoice !=1 and  mchoice !=2:
print("{0} is not a menu option.".format(mchoice))
mchoice = int(raw_input("Please try again> "))


if mchoice == 2:
  filename = raw_input("Hello, please enter file name here> ")
  if filename.endswith(".txt"):

   try:
infile = open(filename)
   except EnvironmentError as e:
print(e)
sys.exit(1)

   print("\nFile {0} exists!".format(filename))
   print("\nGetting IP addresses for hosts")
   print("\n")
  else:
   print("{0} is not a Text file.".format(filename))
   sys.exit(1)
  for line in infile:
hostname = line.strip()
try:
ip_address = socket.gethostbyname(hostname)
except EnvironmentError as e:
print("Couldn't find IP address for {0}: {1}".format(hostname, e))
continue
print("IP address for {0} is {1}.".format(hostname, ip_address))
  else:
print ("\nFinished the operation")

if mchoice == 1:
  murl = raw_input("Enter URL here> ")
  try:
  print("Checking URL...")
  ip_address = socket.gethostbyname(murl)
  except EnvironmentError as d:
  print(d)
  sys.exit(1)
  print("Valid URL")
  print("\nIP address for {0} is {1}.".format(murl, ip_address))
  print ("\nFinished the operation")
=

now where it says Finsihed the operation i want it to show (another search 
/main menu/exit program)

i know about the while loop , but forgive me i just don't have a clue how to 
use it for this situation.

i don't want you to give me the code:) just the idea.
i did read the section about the while loop but still i do not know how to use 
it in this situation.
thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using text file to get ip address from hostname

2012-09-19 Thread Chris Angelico
On Wed, Sep 19, 2012 at 6:50 PM, Dan Katorza  wrote:
> i know about the while loop , but forgive me i just don't have a clue how to 
> use it for this situation.

You've already used one. What you need to do is surround your entire
code with the loop, so that as soon as it gets to the bottom, it goes
back to the top.

Tip: You'll be indenting the bulk of your code.

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


Re: using text file to get ip address from hostname

2012-09-19 Thread Dan Katorza
בתאריך יום רביעי, 19 בספטמבר 2012 11:50:56 UTC+3, מאת Dan Katorza:
> בתאריך יום רביעי, 19 בספטמבר 2012 11:14:29 UTC+3, מאת Chris Angelico:
> 
> > On Wed, Sep 19, 2012 at 5:41 PM, Dan Katorza  wrote:
> 
> > 
> 
> > >
> 
> > 
> 
> > > Hello again,
> 
> > 
> 
> > > I have another question and i hope you will understand me..
> 
> > 
> 
> > > Is there any option where you can set the program to go back to lets say 
> > > the top of the code?
> 
> > 
> 
> > > I mean if the program finished the operation and i want to stay in the 
> > > program and go back ro the start.
> 
> > 
> 
> > > after any operation i want the option to do it again , go back to the 
> > > main menu or full exit from the program, and i want it every time.
> 
> > 
> 
> > >
> 
> > 
> 
> > > i hope i'm clear :)
> 
> > 
> 
> > 
> 
> > 
> 
> > Yep! Look up the docs and tutorial on "control flow" and "looping
> 
> > 
> 
> > constructs". Sounds like what you want here is a 'while' loop.
> 
> > 
> 
> > 
> 
> > 
> 
> > ChrisA
> 
> 
> 
> Hi Chris,
> 
> this is my code:
> 
> 
> 
> #!/usr/bin/env python
> 
> #Get the IP Address
> 
> 
> 
> import sys, socket
> 
> 
> 
> print ("\n\n#")
> 
> print ("#Get IP from Host v 1.0 #")
> 
> print ("#")
> 
> print ("# Choose from the options below #")
> 
> print ("#  1- url , 2-File(Text file only.txt)  #")
> 
> print ("#\n")
> 
> 
> 
> mchoice = int(raw_input("Please enter your choice> "))
> 
> while mchoice !=1 and  mchoice !=2:
> 
> print("{0} is not a menu option.".format(mchoice))
> 
> mchoice = int(raw_input("Please try again> "))
> 
> 
> 
> 
> 
> if mchoice == 2:
> 
>   filename = raw_input("Hello, please enter file name here> ")
> 
>   if filename.endswith(".txt"):
> 
> 
> 
>try:
> 
> infile = open(filename)
> 
>except EnvironmentError as e:
> 
> print(e)
> 
> sys.exit(1)
> 
> 
> 
>print("\nFile {0} exists!".format(filename))
> 
>print("\nGetting IP addresses for hosts")
> 
>print("\n")
> 
>   else:
> 
>print("{0} is not a Text file.".format(filename))
> 
>sys.exit(1)
> 
>   for line in infile:
> 
> hostname = line.strip()
> 
> try:
> 
> ip_address = socket.gethostbyname(hostname)
> 
> except EnvironmentError as e:
> 
> print("Couldn't find IP address for {0}: {1}".format(hostname, e))
> 
> continue
> 
> print("IP address for {0} is {1}.".format(hostname, ip_address))
> 
>   else:
> 
> print ("\nFinished the operation")
> 
> 
> 
> if mchoice == 1:
> 
>   murl = raw_input("Enter URL here> ")
> 
>   try:
> 
>   print("Checking URL...")
> 
>   ip_address = socket.gethostbyname(murl)
> 
>   except EnvironmentError as d:
> 
>   print(d)
> 
>   sys.exit(1)
> 
>   print("Valid URL")
> 
>   print("\nIP address for {0} is {1}.".format(murl, ip_address))
> 
>   print ("\nFinished the operation")
> 
> =
> 
> 
> 
> now where it says Finsihed the operation i want it to show (another search 
> /main menu/exit program)
> 
> 
> 
> i know about the while loop , but forgive me i just don't have a clue how to 
> use it for this situation.
> 
> 
> 
> i don't want you to give me the code:) just the idea.
> 
> i did read the section about the while loop but still i do not know how to 
> use it in this situation.
> 
> thanks.

o.k a giant while loop :)
thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'indent'ing Python in windows bat

2012-09-19 Thread Thomas Rachel

Am 18.09.2012 15:03 schrieb David Smith:


I COULD break down each batch file and write dozens of mini python
scripts to be called. I already have a few, too. Efficiency? Speed is
bad, but these are bat files, after all. The cost of trying to work with
a multitude of small files is high, though, and I realized I had better
go to a mix.


In order to achieve this, it might be very useful to either have a 
module for each (bigger) part to be achieved which you can call with


python -m modulename arg1 arg2 arg3

and putting the Python code into modulename.py.

Or you have one big "interpreter" which works this way:

class Cmd(object):
"""
Command collector
"""
def __init__(self):
self.cmds = {}
def cmd(self, f):
# register a function
self.cmds[f.__name__] = f
return f
def main(self):
import sys
sys.exit(self.cmds[sys.argv[1]](*sys.argv[2:]))

cmd = Cmd()

@cmd.cmd
def cmd1(arg1, arg2):
do_stuff()
...
return 1 # error -> exit()

@cmd.cmd
def cmd2():
...

if __name__ == '__main__':
cmd.main()


This is suitable for many small things and can be used this way:

bat cmds
python -m thismodule cmd1 a b
other bat cmds
python -m thismodule cmd2
...

HTH,

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


Using dict as object

2012-09-19 Thread Pierre Tardy
One thing that is cooler with java-script than in python is that dictionaries 
and objects are the same thing. It allows browsing of complex hierarchical data 
syntactically easy.

For manipulating complex jsonable data, one will always prefer writing:
buildrequest.properties.myprop
rather than
brdict['properties']['myprop']

This ability in JS is well known for its flaws (e.g. 
http://drupal.org/node/172169#forin ), and I understand why this is not a 
feature that we want in python by default. I did work on class that adds this 
feature, and that I wish to use for manipulating my json data.

The following github pull request to buildbot has tests that defines 
specification of such a class, and has several commits, which gives several 
implementation of the same thing.
https://github.com/buildbot/buildbot/pull/525

All implementation I tried are much slower than a pure native dict access. 
Each implementation have bench results in commit comment. All of them are 20+x 
slower than plain dict!
I would like to have python guys advices on how one could optimize this.

I'd like to eventually post this to python-dev, please tell if this is really 
not a good idea.

Regards,
Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess call is not waiting.

2012-09-19 Thread andrea crotti
2012/9/18 Dennis Lee Bieber :
>
> Unless you have a really massive result set from that "ls", that
> command probably ran so fast that it is blocked waiting for someone to
> read the PIPE.

I tried also with "ls -lR /" and that definitively takes a while to run,
when I do this:

proc = subprocess.Popen(['ls', '-lR', '/'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)

nothing is running, only when I actually do
proc.communicate()

I see the process running in top..
Is it still an observation problem?

Anyway I also need to know when the process is over while waiting, so
probably a thread is the only way..
-- 
http://mail.python.org/mailman/listinfo/python-list


A little morning puzzle

2012-09-19 Thread Neal Becker
I have a list of dictionaries.  They all have the same keys.  I want to find 
the 
set of keys where all the dictionaries have the same values.  Suggestions?

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


Re: A little morning puzzle

2012-09-19 Thread Peter Otten
Neal Becker wrote:

> I have a list of dictionaries.  They all have the same keys.  I want to
> find the set of keys where all the dictionaries have the same values.  
Suggestions?

>>> items = [
... {1:2, 2:2},
... {1:1, 2:2},
... ]
>>> first = items[0].items()
>>> [key for key, value in first if all(item[key] == value for item in 
items)]
[2]


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


Re: A little morning puzzle

2012-09-19 Thread Jussi Piitulainen
Neal Becker writes:

> I have a list of dictionaries.  They all have the same keys.  I want
> to find the set of keys where all the dictionaries have the same
> values.  Suggestions?

Literally-ish:
{ key for key, val in ds[0].items() if all(val == d[key] for d in ds) }
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using dict as object

2012-09-19 Thread Dave Angel
On 09/19/2012 06:24 AM, Pierre Tardy wrote:
> One thing that is cooler with java-script than in python is that dictionaries 
> and objects are the same thing. It allows browsing of complex hierarchical 
> data syntactically easy.

You probably need some different terminology, since a dictionary is
already an object.  So's an int, or a list, or anything else visible in
python.  You're trying to blur the distinction between attribute access
and access by key (square brackets).

>
> For manipulating complex jsonable data, one will always prefer writing:
> buildrequest.properties.myprop
> rather than
> brdict['properties']['myprop']

So what you want is to provide a dict-like class which has both a
__getitem__ and a __getattribute__, which produces mostly the same
results, if the parameters happen to be reasonable and not conflict with
other methods.  (Similar for *set*, *del*, and __contains__ and maybe
others).  This has been proposed and discussed and even implemented many
times on this list and others.

> This ability in JS is well known for its flaws (e.g. 
> http://drupal.org/node/172169#forin ), and I understand why this is not a 
> feature that we want in python by default. I did work on class that adds this 
> feature, and that I wish to use for manipulating my json data.

There are many more flaws than just the hiding of certain items because
of existing attributes.  Additionally, this would only work for items
whose keys are strings, and are strings that happen to be legal symbol
names and not keywords.  If you also support __setitem__ or __delitem__
you run the risk of arbitrary code trashing the code that makes the
class work.

> The following github pull request to buildbot has tests that defines 
> specification of such a class, and has several commits, which gives several 
> implementation of the same thing.
> https://github.com/buildbot/buildbot/pull/525
>
> All implementation I tried are much slower than a pure native dict access. 
> Each implementation have bench results in commit comment. All of them are 
> 20+x slower than plain dict!

Assuming you're talking about CPython benchmarks, the dict is highly
optimized, C code.  And when you provide your own __getitem__
implementation in pure python, there are many attribute accesses, just
to make the code work.

> I would like to have python guys advices on how one could optimize this.

Use C code and slots.

> I'd like to eventually post this to python-dev, please tell if this is really 
> not a good idea.
>
> Regards,
> Pierre

if you're proposing a new module for the stdlib, one of the (unstated?)
requirements is that it be in regular use by a fairly large audience for
a while.



-- 

DaveA

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


Re: A little morning puzzle

2012-09-19 Thread Dwight Hutto
> I have a list of dictionaries.  They all have the same keys.  I want to find 
> the
> set of keys where all the dictionaries have the same values.  Suggestions?

Here is my solution:


a = {}
a['dict'] = 1

b = {}
b['dict'] = 2

c = {}
c['dict'] = 1

d = {}
d['dict'] = 3

e = {}
e['dict'] = 1


x = [a,b,c,d,e]
collection_count = 0

for dict_key_search in x:
if dict_key_search['dict'] == 1:
collection_count += 1
print dict_key_search['dict']


Might be better ones though.


-- 
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A little morning puzzle

2012-09-19 Thread Peter Otten
Dwight Hutto wrote:

>> I have a list of dictionaries.  They all have the same keys.  I want to
>> find the
>> set of keys where all the dictionaries have the same values. 
>> Suggestions?
> 
> Here is my solution:
> 
> 
> a = {}
> a['dict'] = 1
> 
> b = {}
> b['dict'] = 2
> 
> c = {}
> c['dict'] = 1
> 
> d = {}
> d['dict'] = 3
> 
> e = {}
> e['dict'] = 1
> 
> 
> x = [a,b,c,d,e]
> collection_count = 0
> 
> for dict_key_search in x:
> if dict_key_search['dict'] == 1:
> collection_count += 1
> print dict_key_search['dict']
> 
> 
> Might be better ones though.

Unlikely. 


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


Re: A little morning puzzle

2012-09-19 Thread Antoon Pardon
On 19-09-12 13:17, Neal Becker wrote:
> I have a list of dictionaries.  They all have the same keys.  I want to find 
> the 
> set of keys where all the dictionaries have the same values.  Suggestions?
common_items = reduce(opereator.__and__, [set(dct.iteritems()) for dct
in lst])
common_keys = set([item[0] for item in common_items])

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


Re: Re: 'indent'ing Python in windows bat

2012-09-19 Thread David Smith

On 2012-09-19 05:22, Thomas Rachel wrote:

Am 18.09.2012 15:03 schrieb David Smith:


I COULD break down each batch file and write dozens of mini python
scripts to be called. I already have a few, too. Efficiency? Speed is
bad, but these are bat files, after all. The cost of trying to work with
a multitude of small files is high, though, and I realized I had better
go to a mix.


In order to achieve this, it might be very useful to either have a
module for each (bigger) part to be achieved which you can call with

...


Or you have one big "interpreter" which works this way:

class Cmd(object):
 """
 Command collector
 """

...
...


This is suitable for many small things and can be used this way:

...

Thomas


Thomas,
Beautiful. Gotta love it. I'll see if I can get the "interpreter" going. 
I particularly like it because I will be able to copy and paste 
wholesale when I stitch the final product back together again. Many thanks.


Going back to the one-liner, I discovered the following individual lines 
work:

print('hi')
if 1: print('hi')
print('hi');print('hi2')
if 1: print('hi');print('hi2')

but not:
print('hi');if 1: print('hi')

Chokes on the 'if'. On the surface, this is not consistent.

I'll drop the one-liners for now since I have something that I can work 
with as I learn to wrestle with Python.


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


Re: A little morning puzzle

2012-09-19 Thread Dwight Hutto
On Wed, Sep 19, 2012 at 8:01 AM, Dwight Hutto  wrote:
>> I have a list of dictionaries.  They all have the same keys.  I want to find 
>> the
>> set of keys where all the dictionaries have the same values.  Suggestions?
>
This one is better:


a = {}
a['dict'] = 1

b = {}
b['dict'] = 2

c = {}
c['dict'] = 1

d = {}
d['dict'] = 3

e = {}
e['dict'] = 1


x = [a,b,c,d,e]
count = 0
collection_count = 0
search_variable = 1
for dict_key_search in x:
if dict_key_search['dict'] == search_variable:
print "Match count found: #%i = %i" % (count,search_variable)
collection_count += 1
count += 1
print collection_count

-- 
Best Regards,
David Hutto
CEO: http://www.hitwebdevelopment.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using text file to get ip address from hostname

2012-09-19 Thread Dan Katorza
בתאריך יום רביעי, 19 בספטמבר 2012 12:11:04 UTC+3, מאת Dan Katorza:
> בתאריך יום רביעי, 19 בספטמבר 2012 11:50:56 UTC+3, מאת Dan Katorza:
> 
> > בתאריך יום רביעי, 19 בספטמבר 2012 11:14:29 UTC+3, מאת Chris Angelico:
> 
> > 
> 
> > > On Wed, Sep 19, 2012 at 5:41 PM, Dan Katorza  wrote:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > >
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > Hello again,
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > I have another question and i hope you will understand me..
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > Is there any option where you can set the program to go back to lets 
> > > > say the top of the code?
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > I mean if the program finished the operation and i want to stay in the 
> > > > program and go back ro the start.
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > after any operation i want the option to do it again , go back to the 
> > > > main menu or full exit from the program, and i want it every time.
> 
> > 
> 
> > > 
> 
> > 
> 
> > > >
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > i hope i'm clear :)
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > Yep! Look up the docs and tutorial on "control flow" and "looping
> 
> > 
> 
> > > 
> 
> > 
> 
> > > constructs". Sounds like what you want here is a 'while' loop.
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > ChrisA
> 
> > 
> 
> > 
> 
> > 
> 
> > Hi Chris,
> 
> > 
> 
> > this is my code:
> 
> > 
> 
> > 
> 
> > 
> 
> > #!/usr/bin/env python
> 
> > 
> 
> > #Get the IP Address
> 
> > 
> 
> > 
> 
> > 
> 
> > import sys, socket
> 
> > 
> 
> > 
> 
> > 
> 
> > print ("\n\n#")
> 
> > 
> 
> > print ("#Get IP from Host v 1.0 #")
> 
> > 
> 
> > print ("#")
> 
> > 
> 
> > print ("# Choose from the options below #")
> 
> > 
> 
> > print ("#  1- url , 2-File(Text file only.txt)  #")
> 
> > 
> 
> > print ("#\n")
> 
> > 
> 
> > 
> 
> > 
> 
> > mchoice = int(raw_input("Please enter your choice> "))
> 
> > 
> 
> > while mchoice !=1 and  mchoice !=2:
> 
> > 
> 
> > print("{0} is not a menu option.".format(mchoice))
> 
> > 
> 
> > mchoice = int(raw_input("Please try again> "))
> 
> > 
> 
> > 
> 
> > 
> 
> > 
> 
> > 
> 
> > if mchoice == 2:
> 
> > 
> 
> >   filename = raw_input("Hello, please enter file name here> ")
> 
> > 
> 
> >   if filename.endswith(".txt"):
> 
> > 
> 
> > 
> 
> > 
> 
> >try:
> 
> > 
> 
> > infile = open(filename)
> 
> > 
> 
> >except EnvironmentError as e:
> 
> > 
> 
> > print(e)
> 
> > 
> 
> > sys.exit(1)
> 
> > 
> 
> > 
> 
> > 
> 
> >print("\nFile {0} exists!".format(filename))
> 
> > 
> 
> >print("\nGetting IP addresses for hosts")
> 
> > 
> 
> >print("\n")
> 
> > 
> 
> >   else:
> 
> > 
> 
> >print("{0} is not a Text file.".format(filename))
> 
> > 
> 
> >sys.exit(1)
> 
> > 
> 
> >   for line in infile:
> 
> > 
> 
> > hostname = line.strip()
> 
> > 
> 
> > try:
> 
> > 
> 
> > ip_address = socket.gethostbyname(hostname)
> 
> > 
> 
> > except EnvironmentError as e:
> 
> > 
> 
> > print("Couldn't find IP address for {0}: {1}".format(hostname, e))
> 
> > 
> 
> > continue
> 
> > 
> 
> > print("IP address for {0} is {1}.".format(hostname, ip_address))
> 
> > 
> 
> >   else:
> 
> > 
> 
> > print ("\nFinished the operation")
> 
> > 
> 
> > 
> 
> > 
> 
> > if mchoice == 1:
> 
> > 
> 
> >   murl = raw_input("Enter URL here> ")
> 
> > 
> 
> >   try:
> 
> > 
> 
> >   print("Checking URL...")
> 
> > 
> 
> >   ip_address = socket.gethostbyname(murl)
> 
> > 
> 
> >   except EnvironmentError as d:
> 
> > 
> 
> >   print(d)
> 
> > 
> 
> >   sys.exit(1)
> 
> > 
> 
> >   print("Valid URL")
> 
> > 
> 
> >   print("\nIP address for {0} is {1}.".format(murl, ip_address))
> 
> > 
> 
> >   print ("\nFinished the operation")
> 
> > 
> 
> > =
> 
> > 
> 
> > 
> 
> > 
> 
> > now where it says Finsihed the operation i want it to show (another search 
> > /main menu/exit program)
> 
> > 
> 
> > 
> 
> > 
> 
> > i know about the while loop , but forgive me i just don't have a clue how 
> > to use it for this situation.
> 
> > 
> 
> > 
> 
> > 
> 
> > i don't want you to give me the code:) just the idea.
> 
> > 
> 
> > i did read the section about the while loop but still i do not know how to 
> > use it in this situation.
> 
> > 
> 
> > thanks.
> 
> 
> 
> o.k a giant while loop :)
> 
> thanks.

hi, 
found a solution,
it's not quite like Chris advised but it works.

#!/usr/bin/env python
#Get the IP Address

import sys, socket, os

def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)

print ("\n\n#")
print ("# 

Re: Decorators not worth the effort

2012-09-19 Thread Jean-Michel Pichavant


- Original Message -
> Jean-Michel Pichavant  writes:
> 
> > - Original Message -
> >> Jean-Michel Pichavant wrote:
> > [snip]
> >> One minor note, the style of decorator you are using loses the
> >> docstring
> >> (at least) of the original function. I would add the
> >> @functools.wraps(func)
> >> decorator inside your decorator.
> >
> > Is there a way to not loose the function signature as well ?
> 
> Look at the "decorator" module.
> 

Great, thank you.

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


Re: subprocess call is not waiting.

2012-09-19 Thread Hans Mulder
On 19/09/12 12:26:30, andrea crotti wrote:
> 2012/9/18 Dennis Lee Bieber :
>>
>> Unless you have a really massive result set from that "ls", that
>> command probably ran so fast that it is blocked waiting for someone to
>> read the PIPE.
> 
> I tried also with "ls -lR /" and that definitively takes a while to run,
> when I do this:
> 
> proc = subprocess.Popen(['ls', '-lR', '/'], stdout=subprocess.PIPE,
> stderr=subprocess.PIPE)
> 
> nothing is running, only when I actually do
> proc.communicate()
> 
> I see the process running in top..
> Is it still an observation problem?

Yes: using "top" is an observation problem.

"Top", as the name suggests, shows only the most active processes.

It's quite possible that your 'ls' process is not active, because
it's waiting for your Python process to read some data from the pipe.

Try using "ps" instead.  Look in thte man page for the correct
options (they differ between platforms).  The default options do
not show all processes, so they may not show the process you're
looking for.

> Anyway I also need to know when the process is over while waiting, so
> probably a thread is the only way..

This sounds confused.

You don't need threads.  When 'ls' finishes, you'll read end-of-file
on the proc.stdout pipe.  You should then call proc.wait() to reap
its exit status (if you don't, you'll leave a zombie process).
Since the process has already finished, the proc.wait() call will
not actually do any waiting.


Hope this helps,

-- HansM


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


Re: Using dict as object

2012-09-19 Thread Oscar Benjamin
On 2012-09-19, Dave Angel  wrote:
> On 09/19/2012 06:24 AM, Pierre Tardy wrote:
>> All implementation I tried are much slower than a pure native dict access.
>> 
 Each implementation have bench results in commit comment. All of them
>> are 20+x slower than plain dict!
>
> Assuming you're talking about CPython benchmarks, the dict is highly
> optimized, C code.  And when you provide your own __getitem__
> implementation in pure python, there are many attribute accesses, just
 to
> make the code work.
>
>> I would like to have python guys advices on how one could optimize this.
>

I agree with all of Dave's objections to this idea. It is possible, however,
to make a more efficient implementation than the one that you have:

class Namespace(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self

This implementation is not really sane, though, as it doesn't hide any of the
dict methods as attributes. It does, however, demonstrate something that be a
potentially simple way of making an alternate type object in C.

Oscar

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


Re: Using dict as object

2012-09-19 Thread Thomas Rachel

Am 19.09.2012 12:24 schrieb Pierre Tardy:


One thing that is cooler with java-script than in python is that dictionaries 
and objects are the same thing. It allows browsing of complex hierarchical data 
syntactically easy.

For manipulating complex jsonable data, one will always prefer writing:
buildrequest.properties.myprop
rather than
brdict['properties']['myprop']


This is quite easy to achieve (but not so easy to understand):

class JsObject(dict):
def __init__(self, *args, **kwargs):
super(JsObject, self).__init__(*args, **kwargs)
self.__dict__ = self

(Google for JSObject; this is not my courtesy).

What does it do? Well, an object's attributes are stored in a dict. If I 
subclass dict, the resulting class can be used for this as well.


In this case, a subclass of a dict gets itself as its __dict__. What 
happens now is


d = JsObject()

d.a = 1
print d['a']

# This results in d.__dict__['a'] = 1.
# As d.__dict__ is d, this is equivalent to d['a'] = 1.

# Now the other way:

d['b'] = 42
print d.b

# here as well: d.b reads d.__dict__['b'], which is essentially d['b'].


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


sum works in sequences (Python 3)

2012-09-19 Thread Franck Ditter
Hello,
I wonder why sum does not work on the string sequence in Python 3 :

>>> sum((8,5,9,3))
25
>>> sum([5,8,3,9,2])
27
>>> sum('rtarze')
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I naively thought that sum('abc') would expand to 'a'+'b'+'c' 
And the error message is somewhat cryptic...

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


Re: sum works in sequences (Python 3)

2012-09-19 Thread Joel Goldstick
On Wed, Sep 19, 2012 at 10:41 AM, Franck Ditter  wrote:
> Hello,
> I wonder why sum does not work on the string sequence in Python 3 :
>
 sum((8,5,9,3))
> 25
 sum([5,8,3,9,2])
> 27
 sum('rtarze')
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I naively thought that sum('abc') would expand to 'a'+'b'+'c'
> And the error message is somewhat cryptic...
>
> franck
> --
> http://mail.python.org/mailman/listinfo/python-list
Help on built-in function sum in module __builtin__:

sum(...)
sum(sequence[, start]) -> value

Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the sequence is
empty, returns start.
~



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


Re: sum works in sequences (Python 3)

2012-09-19 Thread Neil Cerutti
On 2012-09-19, Franck Ditter  wrote:
> Hello,
> I wonder why sum does not work on the string sequence in Python 3 :
>
 sum((8,5,9,3))
> 25
 sum([5,8,3,9,2])
> 27
 sum('rtarze')
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I naively thought that sum('abc') would expand to 'a'+'b'+'c'
> And the error message is somewhat cryptic...

You got that error message because the default value for the
second 'start' argument is 0. The function tried to add 'r' to 0.
That said:

>>> sum('rtarze', '')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: sum() can't sum strings [use ''.join(seq) instead]

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


Re: sum works in sequences (Python 3)

2012-09-19 Thread Ian Kelly
On Wed, Sep 19, 2012 at 8:41 AM, Franck Ditter  wrote:
> Hello,
> I wonder why sum does not work on the string sequence in Python 3 :
>
 sum((8,5,9,3))
> 25
 sum([5,8,3,9,2])
> 27
 sum('rtarze')
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I naively thought that sum('abc') would expand to 'a'+'b'+'c'
> And the error message is somewhat cryptic...

It notes in the doc string that it does not work on strings:

sum(...)
sum(sequence[, start]) -> value

Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the sequence is
empty, returns start.

I think this restriction is mainly for efficiency.  sum(['a', 'b',
'c', 'd', 'e']) would be the equivalent of 'a' + 'b' + 'c' + 'd' +
'e', which is an inefficient way to add together strings.  You should
use ''.join instead:

>>> ''.join('abc')
'abc'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Neil Cerutti
On 2012-09-19, Ian Kelly  wrote:
> It notes in the doc string that it does not work on strings:
>
> sum(...)
> sum(sequence[, start]) -> value
>
> Returns the sum of a sequence of numbers (NOT strings) plus
> the value of parameter 'start' (which defaults to 0).  When
> the sequence is empty, returns start.
>
> I think this restriction is mainly for efficiency.  sum(['a',
> 'b', 'c', 'd', 'e']) would be the equivalent of 'a' + 'b' + 'c'
> + 'd' + 'e', which is an inefficient way to add together
> strings.  You should use ''.join instead:

While the docstring is still useful, it has diverged from the
documentation a little bit.

  sum(iterable[, start]) 

  Sums start and the items of an iterable from left to right and
  returns the total. start defaults to 0. The iterable‘s items
  are normally numbers, and the start value is not allowed to be
  a string.

  For some use cases, there are good alternatives to sum(). The
  preferred, fast way to concatenate a sequence of strings is by
  calling ''.join(sequence). To add floating point values with
  extended precision, see math.fsum(). To concatenate a series of
  iterables, consider using itertools.chain().

Are iterables and sequences different enough to warrant posting a
bug report?

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


Re: sum works in sequences (Python 3)

2012-09-19 Thread Alister
On Wed, 19 Sep 2012 16:41:20 +0200, Franck Ditter wrote:

> Hello,
> I wonder why sum does not work on the string sequence in Python 3 :
> 
 sum((8,5,9,3))
> 25
 sum([5,8,3,9,2])
> 27
 sum('rtarze')
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
> 
> I naively thought that sum('abc') would expand to 'a'+'b'+'c'
> And the error message is somewhat cryptic...
> 
> franck

Summation is a mathematical function that works on numbers
Concatenation is the process of appending 1 string to another

although they are not related to each other they do share the same 
operator(+) which is the cause of confusion.
attempting to duck type this function would cause ambiguity for example 
what would you expect from

sum ('a','b',3,4)

'ab34' or 'ab7' ?

even 'A' + 7 would return this error for same reason.
 



-- 
It is the nature of extreme self-lovers, as they will set an house on 
fire,
and it were but to roast their eggs.
-- Francis Bacon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A little morning puzzle

2012-09-19 Thread Ian Kelly
On Wed, Sep 19, 2012 at 6:13 AM, Antoon Pardon
 wrote:
> On 19-09-12 13:17, Neal Becker wrote:
>> I have a list of dictionaries.  They all have the same keys.  I want to find 
>> the
>> set of keys where all the dictionaries have the same values.  Suggestions?
> common_items = reduce(opereator.__and__, [set(dct.iteritems()) for dct
> in lst])
> common_keys = set([item[0] for item in common_items])

You can use dictviews for that:

common_items = reduce(operator.__and__, (d.viewitems() for d in ds))
common_keys = [item[0] for item in common_items]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Ian Kelly
On Wed, Sep 19, 2012 at 9:06 AM, Neil Cerutti  wrote:
> Are iterables and sequences different enough to warrant posting a
> bug report?

The glossary is specific about the definitions of both, so I would say yes.

http://docs.python.org/dev/glossary.html#term-iterable
http://docs.python.org/dev/glossary.html#term-sequence
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Steve Howell
On Sep 19, 8:06 am, Neil Cerutti  wrote:
> On 2012-09-19, Ian Kelly  wrote:
>
> > It notes in the doc string that it does not work on strings:
>
> > sum(...)
> >     sum(sequence[, start]) -> value
>
> >     Returns the sum of a sequence of numbers (NOT strings) plus
> >     the value of parameter 'start' (which defaults to 0).  When
> >     the sequence is empty, returns start.
>
> > I think this restriction is mainly for efficiency.  sum(['a',
> > 'b', 'c', 'd', 'e']) would be the equivalent of 'a' + 'b' + 'c'
> > + 'd' + 'e', which is an inefficient way to add together
> > strings.  You should use ''.join instead:
>
> While the docstring is still useful, it has diverged from the
> documentation a little bit.
>
>   sum(iterable[, start])
>
>   Sums start and the items of an iterable from left to right and
>   returns the total. start defaults to 0. The iterable‘s items
>   are normally numbers, and the start value is not allowed to be
>   a string.
>
>   For some use cases, there are good alternatives to sum(). The
>   preferred, fast way to concatenate a sequence of strings is by
>   calling ''.join(sequence). To add floating point values with
>   extended precision, see math.fsum(). To concatenate a series of
>   iterables, consider using itertools.chain().
>
> Are iterables and sequences different enough to warrant posting a
> bug report?
>

Sequences are iterables, so I'd say the docs are technically correct,
but maybe I'm misunderstanding what you would be trying to clarify.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess call is not waiting.

2012-09-19 Thread Gene Heskett
On Wednesday 19 September 2012 11:56:44 Hans Mulder did opine:

> On 19/09/12 12:26:30, andrea crotti wrote:
> > 2012/9/18 Dennis Lee Bieber :
> >> Unless you have a really massive result set from that "ls",
> >> that
> >> 
> >> command probably ran so fast that it is blocked waiting for someone
> >> to read the PIPE.
> > 
> > I tried also with "ls -lR /" and that definitively takes a while to
> > run, when I do this:
> > 
> > proc = subprocess.Popen(['ls', '-lR', '/'], stdout=subprocess.PIPE,
> > stderr=subprocess.PIPE)
> > 
> > nothing is running, only when I actually do
> > proc.communicate()
> > 
> > I see the process running in top..
> > Is it still an observation problem?
> 
> Yes: using "top" is an observation problem.
> 
> "Top", as the name suggests, shows only the most active processes.
> 
Which is why I run htop in a shell 100% of the time.  With htop, you can 
scroll down and see everything.

> It's quite possible that your 'ls' process is not active, because
> it's waiting for your Python process to read some data from the pipe.
> 
> Try using "ps" instead.  Look in thte man page for the correct
> options (they differ between platforms).  The default options do
> not show all processes, so they may not show the process you're
> looking for.
> 
> > Anyway I also need to know when the process is over while waiting, so
> > probably a thread is the only way..
> 
> This sounds confused.
> 
> You don't need threads.  When 'ls' finishes, you'll read end-of-file
> on the proc.stdout pipe.  You should then call proc.wait() to reap
> its exit status (if you don't, you'll leave a zombie process).
> Since the process has already finished, the proc.wait() call will
> not actually do any waiting.
> 
> 
> Hope this helps,
> 
> -- HansM


Cheers, Gene
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
My web page:  is up!
To know Edina is to reject it.
-- Dudley Riggs, "The Year the Grinch Stole the Election"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Steven D'Aprano
On Wed, 19 Sep 2012 09:03:03 -0600, Ian Kelly wrote:

> I think this restriction is mainly for efficiency.  sum(['a', 'b', 'c',
> 'd', 'e']) would be the equivalent of 'a' + 'b' + 'c' + 'd' + 'e', which
> is an inefficient way to add together strings.

It might not be obvious to some people why repeated addition is so 
inefficient, and in fact if people try it with modern Python (version 2.3 
or better), they may not notice any inefficiency.

But the example given, 'a' + 'b' + 'c' + 'd' + 'e', potentially ends up 
creating four strings, only to immediately throw away three of them:

* first it concats 'a' to 'b', giving the new string 'ab'
* then 'ab' + 'c', creating a new string 'abc'
* then 'abc' + 'd', creating a new string 'abcd'
* then 'abcd' + 'e', creating a new string 'abcde'

Each new string requires a block of memory to be allocated, potentially 
requiring other blocks of memory to be moved out of the way (at least for 
large blocks).

With only five characters in total, you won't really notice any slowdown, 
but with large enough numbers of strings, Python could potentially spend 
a lot of time building, and throwing away, intermediate strings. Pure 
wasted effort.

For another look at this, see:
http://www.joelonsoftware.com/articles/fog000319.html

I say "could" because starting in about Python 2.3, there is a nifty 
optimization in Python (CPython only, not Jython or IronPython) that can 
*sometimes* recognise repeated string concatenation and make it less 
inefficient. It depends on the details of the specific strings used, and 
the operating system's memory management. When it works, it can make 
string concatenation almost as efficient as ''.join(). When it doesn't 
work, repeated concatenation is PAINFULLY slow, hundreds or thousands of 
times slower than join.


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


Re: Using dict as object

2012-09-19 Thread Pierre Tardy
>
>  This has been proposed and discussed and even implemented many
> times on this list and others.
>
I can find this question on SO
http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
which is basically answered with this solution

class AttributeDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__


but this does not allow recursive access, you would need to first convert
all nested dictionaries to AttributeDict.
a.b.c.d = 2 # fail
a.b = dict(c=3)
a.b.c=4 # fail

> I would like to have python guys advices on how one could optimize this.
>
> Use C code and slots.
>
I tried adding __slots__= [], to my class, but my benchmarks do not show
significant changes.


if you're proposing a new module for the stdlib, one of the (unstated?)
> requirements is that it be in regular use by a fairly large audience for
> a while.
>
I was talking about escalading to python-dev as a way to hit more
expertize, but it looks like this one is already
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Steven D'Aprano
On Wed, 19 Sep 2012 15:07:04 +, Alister wrote:

> Summation is a mathematical function that works on numbers Concatenation
> is the process of appending 1 string to another
> 
> although they are not related to each other they do share the same
> operator(+) which is the cause of confusion. attempting to duck type
> this function would cause ambiguity for example what would you expect
> from
> 
> sum ('a','b',3,4)
> 
> 'ab34' or 'ab7' ?

Neither. I would expect sum to do exactly what the + operator does if 
given two incompatible arguments: raise an exception.

And in fact, that's exactly what it does.

py> sum ([1, 2, 'a'])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'str'



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


Re: subprocess call is not waiting.

2012-09-19 Thread andrea crotti
2012/9/19 Hans Mulder :
> Yes: using "top" is an observation problem.
>
> "Top", as the name suggests, shows only the most active processes.

Sure but "ls -lR /" is a very active process if you try to run it..
Anyway as written below I don't need this anymore.

>
> It's quite possible that your 'ls' process is not active, because
> it's waiting for your Python process to read some data from the pipe.
>
> Try using "ps" instead.  Look in thte man page for the correct
> options (they differ between platforms).  The default options do
> not show all processes, so they may not show the process you're
> looking for.
>
>> Anyway I also need to know when the process is over while waiting, so
>> probably a thread is the only way..
>
> This sounds confused.
>
> You don't need threads.  When 'ls' finishes, you'll read end-of-file
> on the proc.stdout pipe.  You should then call proc.wait() to reap
> its exit status (if you don't, you'll leave a zombie process).
> Since the process has already finished, the proc.wait() call will
> not actually do any waiting.
>
>
> Hope this helps,
>


Well there is a process which has to do two things, monitor
periodically some external conditions (filesystem / db), and launch a
process that can take very long time.

So I can't put a wait anywhere, or I'll stop everything else.  But at
the same time I need to know when the process is finished, which I
could do but without a wait might get hacky.

So I'm quite sure I just need to run the subprocess in a subthread
unless I'm missing something obvious..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python presentations

2012-09-19 Thread andrea crotti
2012/9/19 Trent Nelson :
>
> FWIW, I gave a presentation on decorators to the New York Python
> User Group back in 2008.  Relevant blog post:
>
> http://blogs.onresolve.com/?p=48
>
> There's a link to the PowerPoint presentation I used in the first
> paragraph.  It's in .pptx format; let me know if you'd like it in
> some other form.
>
> Regards,
>
> Trent.


Ok thanks a lot, how long did it take for you to present that material?

Interesting the part about the learning process, I had a similar
experience, but probably skip this since I only have 30 minutes.

Another thing which I would skip or only explain how it works are
parametrized decorators, in the triple-def form they just look to ugly
to be worth the effort (but at least should be understood).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess call is not waiting.

2012-09-19 Thread Benjamin Kaplan
On Sep 19, 2012 9:37 AM, "andrea crotti"  wrote:
> Well there is a process which has to do two things, monitor
> periodically some external conditions (filesystem / db), and launch a
> process that can take very long time.
>
> So I can't put a wait anywhere, or I'll stop everything else.  But at
> the same time I need to know when the process is finished, which I
> could do but without a wait might get hacky.
>
> So I'm quite sure I just need to run the subprocess in a subthread
> unless I'm missing something obvious.

If you want to see if a processes has terminated without waiting, use poll.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A little morning puzzle

2012-09-19 Thread Paul Rubin
Neal Becker  writes:
> I have a list of dictionaries.  They all have the same keys.  I want to find 
> the 
> set of keys where all the dictionaries have the same values.  Suggestions?

Untested, and uses a few more comparisons than necessary:

# ds = [dict1, dict2 ... ]

d0 = ds[0]
ks = set(k for k in d0 if all(d[k]==d0[k] for d in ds))
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Ismael Farfán
Hello list

>From man 2 EXECVE
"By default, file descriptors remain open across an execve()"

And from man 2 FCNTL
"Record locks are... preserved across an execve(2)."

So the question:
* If I execve a python script (from C), how can I retrieve the list of
files, and optionally the list of locks, from within the execve(d)
python process so that I can use them?


Some more info:
I'm working with exotic stuff like AIX and Solaris 10 (Windows and
linux too :) and my lowest common denominator is python 2.3.

>From a standalone test within the interpreter I'd expect to get (at
least) std(in/out/err).

If more information is needed in order to help me, please let me know.

Cheers
Ismael


-- 
Do not let me induce you to satisfy my curiosity, from an expectation,
that I shall gratify yours. What I may judge proper to conceal, does
not concern myself alone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess call is not waiting.

2012-09-19 Thread Hans Mulder
On 19/09/12 18:34:58, andrea crotti wrote:
> 2012/9/19 Hans Mulder :
>> Yes: using "top" is an observation problem.
>>
>> "Top", as the name suggests, shows only the most active processes.
> 
> Sure but "ls -lR /" is a very active process if you try to run it..

Not necessarily:

>> It's quite possible that your 'ls' process is not active because
>> it's waiting for your Python process to read some data from the pipe.

Hope this helps,

-- HansM

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


Re: 'indent'ing Python in windows bat

2012-09-19 Thread Albert Hopkins
On Tue, 2012-09-18 at 22:12 -0600, Jason Friedman wrote:
> > I'm converting windows bat files little by little to Python 3 as I find time
> > and learn Python.
> > The most efficient method for some lines is to call Python like:
> > python -c "import sys; sys.exit(3)"
> >
> > How do I "indent" if I have something like:
> > if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
> > sys.exit(3)
> 
> Some months ago I posted what I think is a similar question in the
> Unix world:  I wanted to call a small portion of Python from within a
> Bash script.
> 
> Someone on this list answered (for Bash):
> 
> #!/bin/bash
> command1
> command2
> python -c "if True:
> import module
> if condition:
> do_this
> else:
> do_that
> "
> command4
> # end code

A better way (in *nix) would be, e.g.:

#!/bin/sh   
 

read -p 'Enter a number ' count

python << EOF
print 'Odd numbers between 0 and ${count}'
for i in range(${count}):
if i % 2:
print i
EOF

Horribly bad example, but you get the idea.

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


Re: 'indent'ing Python in windows bat

2012-09-19 Thread Terry Reedy

On 9/19/2012 8:27 AM, David Smith wrote:


but not:
print('hi');if 1: print('hi')

Chokes on the 'if'. On the surface, this is not consistent.


Yes it is. ; can only be followed by simple statements. The keyword for 
compound statememts must be the first non-indent token on a line. That 
is why I suggested at the beginning of the thread to insert '\n', 
stating correctly that it works for exec().


>>> exec("print('hi');if 1: print('hi')")
Traceback (most recent call last):
  File "", line 1, in 
exec("print('hi');if 1: print('hi')")
  File "", line 1
print('hi');if 1: print('hi')
 ^
SyntaxError: invalid syntax
>>> exec("print('hi');\nif 1: print('hi')")
hi
hi
>>> exec("print('hi')\nif 1: print('hi')")
hi
hi

Someone raised the issue of whether the bat interpreter passes along the 
quoted string unchanged or if it interprets '\' or '\n' itself and in 
the latter case whether one to do anything so that python will see '\n' 
after any fiddling by the bat interpreter. It seems that \ is not 
interpreted within strngs by bat, but the problem is that the string is 
then seen by python as code, not as a string literal, and so python does 
not 'cook' it either. Running tem.bat from a command line (which echoes 
line from .bat), so I see the output, I get (Win7)


C:\Programs\Python33>python -c "print(1)\nif 1: print(2)"
  File "", line 1
print(1)\nif 1: print(2)
   ^
SyntaxError: unexpected character after line continuation character

One gets the same response interactively from
>>> print('hi')\nif 1: print('hi')
or
>>> exec("print('hi')\\nif 1: print('hi')")

The fix is to quote and pass the exact code that worked above in the 
python shell, keeping in mind that the outer quotes must be the double 
quote characters recognized by windows.


C:\Programs\Python33>python -c "exec('print(1)\nif 1: print(2)')"
1
2

I did check that windows % interpolation of .bat args works within '' 
quoted strings. Change tem.bat to

python -c "exec('print(%1)\nif 1: print(2)')"
and calling 'tem 3' prints
3
2

That said, if you have many multiline statements, putting them in a 
separate file or files may be a good idea.


--
Terry Jan Reedy

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


Re: using text file to get ip address from hostname

2012-09-19 Thread Dave Angel
On 09/19/2012 08:28 AM, Dan Katorza wrote:
> בתאריך יום רביעי, 19 בספטמבר 2012 12:11:04 UTC+3, מאת Dan Katorza:
>> 
>> hi, ll like
>> found a solution,
>> it's not quite like Chris advised but it works.

Not at all like Chris advised.  But it also doesn't help you understand
programming.  Two concepts you're going to have to get a lot more
comfortable with, in Python, or in some other language.  One is loops,
and the other is functions.
>> #!/usr/bin/env python
>> #Get the IP Address
>>
>> import sys, socket, os
>>
>> def restart_program():
>> python = sys.executable
>> os.execl(python, python, * sys.argv)
>>
>> print ("\n\n#")
>> print ("#Get IP from Host v 1.0 #")
>> print ("#")
>> print ("# Choose from the options below #")
>> print ("#  1- url , 2-File(Text file only.txt)  #")
>> print ("#\n")
>>
>> mchoice = int(raw_input("Please enter your choice> "))
>> while mchoice !=1 and  mchoice !=2:
>> print("{0} is not a menu option.".format(mchoice))
>> mchoice = int(raw_input("Please try again> "))
>>
>>
>> while mchoice == 2:
>> filename = raw_input("Please enter file name here> ")
>> if filename.endswith(".txt"):
>>
>> try:
>> infile = open(filename)
>> except EnvironmentError as e:
>> print(e)
>> sys.exit(1)
>>
>> print("\nFile {0} exists!".format(filename))
>> print("\nGetting IP addresses for hosts")
>> print("\n")
>> else:
>> print("{0} is not a Text file.".format(filename))
>> sys.exit(1)
>> for line in infile:
>> hostname = line.strip()
>> try:
>> ip_address = socket.gethostbyname(hostname)
>> except EnvironmentError as e:
>> print("Couldn't find IP address for {0}: {1}".format(hostname, 
>> e))
>> continue
>> print("IP address for {0} is {1}.".format(hostname, ip_address))
>> else:
>> print ("\nFinished the operation")
>> print ("A=another search, M=main menu, E=exit")
>>
>> waction=raw_input("Please choose your action > ")
>>
>> while waction !='A' and waction !='M' and waction !='E':
>> print("{0} is not a valid action.".format(waction))
>> waction=raw_input("Please try again> ")
>> if waction =='E':
>> sys.exit(1)
>> if waction =='A':
>> continue
>> if waction =='M':
>> print 
>> ("#")
>> print ("# Choose from the options below 
>> #")
>> print ("#  1- url , 2-File(Text file only.txt)  
>> #")
>> print 
>> ("#\n")
>>
>> mchoice = int(raw_input("Please enter your choice> "))
>> while mchoice !=1 and  mchoice !=2:
>> print("{0} is not a menu option.".format(mchoice))
>> mchoice = int(raw_input("Please try again> "))
>>
>>
>> while mchoice == 1:
>> murl = raw_input("Enter URL here> ")
>> try:
>> print("Checking URL...")
>> ip_address = socket.gethostbyname(murl)
>> except EnvironmentError as d:
>> print(d)
>> sys.exit(1)
>> print("Valid URL")
>> print("\nIP address for {0} is {1}.".format(murl, ip_address))
>> print ("\nFinished the operation")
>> print ("A=another search, M=main menu, E=exit")
>>
>> waction=raw_input("Please choose your action > ")
>>
>> while waction !='A' and waction !='M' and waction !='E':
>> print("{0} is not a valid action.".format(waction))
>> waction=raw_input("Please try again> ")
>> if waction =='E':
>> sys.exit(1)
>> if waction =='A':
>> continue
>> if waction =='M':
>> restart_program()
>>
>>
>>
>>
This is one enormous top-level code, and when you needed to enclose it
in a loop, your answer is to start a new process!  You also duplicate
quite a few lines, rather than making a function for them, and calling
it from two places.


-- 

DaveA

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


Re: 'indent'ing Python in windows bat

2012-09-19 Thread Hans Mulder
On 19/09/12 19:51:44, Albert Hopkins wrote:
> On Tue, 2012-09-18 at 22:12 -0600, Jason Friedman wrote:
>>> I'm converting windows bat files little by little to Python 3 as I find time
>>> and learn Python.
>>> The most efficient method for some lines is to call Python like:
>>> python -c "import sys; sys.exit(3)"
>>>
>>> How do I "indent" if I have something like:
>>> if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
>>> sys.exit(3)
>>
>> Some months ago I posted what I think is a similar question in the
>> Unix world:  I wanted to call a small portion of Python from within a
>> Bash script.
>>
>> Someone on this list answered (for Bash):
>>
>> #!/bin/bash
>> command1
>> command2
>> python -c "if True:
>> import module
>> if condition:
>> do_this
>> else:
>> do_that
>> "
>> command4
>> # end code
> 
> A better way (in *nix) would be, e.g.:
> 
> #!/bin/sh 
>
> 
> read -p 'Enter a number ' count
> 
> python << EOF
> print 'Odd numbers between 0 and ${count}'
> for i in range(${count}):
> if i % 2:
> print i
> EOF
> 
> Horribly bad example, but you get the idea.

If you do it like that, you have to remember to not use certain
punctuation characters in your Python code, because they are
meaningful to the shell, even inside a 

using uwsgi to get flask going

2012-09-19 Thread Littlefield, Tyler

Hello all:
This is my first shot with UWSGI and Python on Nginx, and I'm getting 
kind of confused.

My uwsgi init script looks like:
#!/bin/sh
#/etc/init.d/uwsgi
### BEGIN INIT INFO
# Provides: uwsgi
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO
PID="/var/run/uwsgi/uwsgi.pid"
SOCKET="/var/run/uwsgi/uwsgi.sock"
DAEMON="/usr/local/bin/uwsgi"
LOGFILE="/var/log/uwsgi.log"
ARGS="--master --socket $SOCKET -d --workers 4 --pidfile $PID --vacuum 
--max-requests 400 --gid uwsgi --uid uwsgi --logto2 $LOGFILE --chdir2 
/opt/nginx/html/falcon -w app:app"

case "$1" in
start)
echo "Starting uwsgi"
touch $SOCKET
touch $LOGFILE
chown uwsgi:uwsgi $LOGFILE
chmod 660 $LOGFILE
chown -R www-data:uwsgi $SOCKET
chmod 660 $SOCKET
start-stop-daemon -p $PID --start --exec $DAEMON -- $ARGS
;;
stop)
echo "Stopping uwsgi."
start-stop-daemon --signal INT -p $PID --stop $DAEMON -- $ARGS
;;
restart)
echo "Stopping uwsgi."
start-stop-daemon --signal INT -p $PID --stop $DAEMON -- $ARGS
echo "Starting uwsgi"
start-stop-daemon -p $PID --start --exec $DAEMON -- $ARGS
;;
*)
echo "Usage: /etc/init.d/uwsgi stop|stop|restart."
exit 1
;;
esac
I'm trying to chdir so I can use app:app (ap.py is the script, app is 
the application in app.py). From what I understand, uwsgi just spawns a 
Python process and runs app.py to handle requests? It doesn't spawn a 
process per instance? How easy would it be to force it to use PyPy for 
example?

Also my nginx config:
server {
server_name www.dev.tds-solutions.net dev.tds-solutions.net;
listen   80;
access_log  logs/dev.access.log;

location / {
root   html/falcon;
index  index.html index.htm;
try_files $uri @uwsgi;
}

location ~ /\.ht {
   deny  all;
}

location @uwsgi {
include /opt/nginx/conf/uwsgi_params;
uwsgi_pass unix:/var/run/uwsgi/uwsgi.sock;
}
}
anyone see anything wrong? Any info would be greatly appreciated.

--
Take care,
Ty
http://tds-solutions.net
The aspen project: a barebones light-weight mud engine:
http://code.google.com/p/aspenmud
He that will not reason is a bigot; he that cannot reason is a fool; he that 
dares not reason is a slave.

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


Re: sum works in sequences (Python 3)

2012-09-19 Thread Ian Kelly
On Wed, Sep 19, 2012 at 9:37 AM, Steve Howell  wrote:
> Sequences are iterables, so I'd say the docs are technically correct,
> but maybe I'm misunderstanding what you would be trying to clarify.

The doc string suggests that the argument to sum() must be a sequence,
when in fact any iterable will do.  The restriction in the docs should
be relaxed to match the reality.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Steve Howell
On Sep 19, 11:34 am, Ian Kelly  wrote:
> On Wed, Sep 19, 2012 at 9:37 AM, Steve Howell  wrote:
> > Sequences are iterables, so I'd say the docs are technically correct,
> > but maybe I'm misunderstanding what you would be trying to clarify.
>
> The doc string suggests that the argument to sum() must be a sequence,
> when in fact any iterable will do.  The restriction in the docs should
> be relaxed to match the reality.

Ah.  The docstring looks to be fixed in 3.1.3, but not in Python 2.


Python 3.1.3 (r313:86834, Mar 13 2011, 00:40:38)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> sum.__doc__
"sum(iterable[, start]) -> value\n\nReturns the sum of an iterable of
numbers (NOT strings) plus the value\nof parameter 'start' (which
defaults to 0).  When the iterable is\nempty, returns start."


Python 2.6.6 (r266:84292, Mar 13 2011, 00:35:19)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> sum.__doc__
"sum(sequence[, start]) -> value\n\nReturns the sum of a sequence of
numbers (NOT strings) plus the value\nof parameter 'start' (which
defaults to 0).  When the sequence is\nempty, returns start."
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Terry Reedy

On 9/19/2012 11:07 AM, Alister wrote:


Summation is a mathematical function that works on numbers
Concatenation is the process of appending 1 string to another

although they are not related to each other they do share the same
operator(+) which is the cause of confusion.


If one represents counts in unary, as a sequence or tally of 1s (or 
other markers indicating 'successor' or 'increment'), then count 
addition is sequence concatenation. I think Guido got it right.


It happens that when the members of all sequences are identical, there 
is a much more compact exponential place value notation that enables 
more efficient addition and other operations. When not, other tricks are 
needed to avoid so much copying that an inherently O(N) operation 
balloons into an O(N*N) operation.


--
Terry Jan Reedy

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


Re: How to send email programmatically from a gmail email a/c when port 587(smtp) is blocked

2012-09-19 Thread ashish
Folks,

I asked the same query on the python tutor mailing list.
The responses i received are here :
http://thread.gmane.org/gmane.comp.python.tutor/77601


Mark,

There is nothing wrong in asking a query on multiple forums.

Poeple on the tutor list, may not be part of comp.lang.python & subscribers to 
comp.lang.python

On Wednesday, September 12, 2012 4:18:05 AM UTC+5:30, Mark Lawrence wrote:
> On 11/09/2012 22:51, ashish makani wrote:
> 
> > Hi c.l.p peeps
> 
> >
> 
> > I am stuck with an issue, so am coming to the Pythonista deltaforce who 
> > rescue me everytime :)
> 
> >
> 
> 
> 
> [big snip]
> 
> 
> 
> I say old chap, it's simply not cricket to ask a question like this some 
> 
> 32 minutes after asking the same question on the tutor mailing list.
> 
> 
> 
> -- 
> 
> Cheers.
> 
> 
> 
> Mark Lawrence.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python presentations

2012-09-19 Thread 88888 Dihedral
andrea crotti於 2012年9月20日星期四UTC+8上午12時42分50秒寫道:
> 2012/9/19 Trent Nelson :
> 
> >
> 
> > FWIW, I gave a presentation on decorators to the New York Python
> 
> > User Group back in 2008.  Relevant blog post:
> 
> >
> 
> > http://blogs.onresolve.com/?p=48
> 
> >
> 
> > There's a link to the PowerPoint presentation I used in the first
> 
> > paragraph.  It's in .pptx format; let me know if you'd like it in
> 
> > some other form.
> 
> >
> 
> > Regards,
> 
> >
> 
> > Trent.
> 
> 
> 
> 
> 
> Ok thanks a lot, how long did it take for you to present that material?
> 
> 
> 
> Interesting the part about the learning process, I had a similar
> 
> experience, but probably skip this since I only have 30 minutes.
> 
> 
> 
> Another thing which I would skip or only explain how it works are
> 
> parametrized decorators, in the triple-def form they just look to ugly
> 
> to be worth the effort (but at least should be understood).

I think the decorator part is reasonable in testing and prototyping.

Every layor of some decorator just adds more overheads, therefore, 
the syntax sugar of the symbol @ just reminds the programmer the fact.

Acctually writing better wrappers for non-trivial enhancements
to objects or functions should be practiced by professionals.

It is easy to import objects written by others in python. 

It is also user responsible to test and enhance the objects 
from others by decorators, the unittest module, or whatever suitable.


I love to play with functions with a varable representing the time
in writing computer games that emulate  hundreds  to thousands of 
animated obects.









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


Passing arguments to & executing, a python script on a remote machine from a python script on local machine

2012-09-19 Thread ashish
Hi PyTutor Folks

Here is my situation

1. I have two machines. Lets call them local & remote.
Both run ubuntu & both have python installed

2. I have a python script, local.py, running on local which needs to pass 
arguments ( 3/4 string arguments, containing whitespaces like spaces, etc ) to 
a python script, remote.py running on remote (the remote machine).

I have the following questions:

1. What's the best way to accomplish my task ?
I have researched quite a bit & so far found really conflicting & complex 
workarounds. 

I googled & found people using several libraries to accomplish ssh to remote 
machine & execute a command on remote machine.
paramiko ( now forked into the ssh moduke), fabric, pushy ,etc

People who have used any of these libraries, which one would you recommend, as 
the most apt (simple & easy to use, lightweight, best performance, etc) for my 
situation ?

2. I would prefer a solution, which does NOT require the installation of extra 
libraries on the local & remote machines.
If installing external librar

3. Has anybody been able to do this using os.system ?

I tried this
>>> import os
>>> os.system ("ssh remoteuser@remote python remote.py arg1 arg2 arg3")

This worked, but if the arguments i tried to pass, had spaces, i was not able 
to 'escape' the spaces.

Any & all explanations/links/code 
snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor 
community would be greatly appreciated.

Thanks a ton

cheers
ashish

email : 
ashish.makani
domain:gmail.com

“The only way to do great work is to love what you do. If you haven’t found it 
yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know 
when you find it.” - Steve Jobs (1955 - 2011)
-- 
http://mail.python.org/mailman/listinfo/python-list


Passing arguments to & executing, a python script on a remote machine from a python script on local machine (using ssh ?)

2012-09-19 Thread ashish
Hi c.l.p folks

Here is my situation

1. I have two machines. Lets call them 'local' & 'remote'.
Both run ubuntu & both have python installed

2. I have a python script, local.py, running on 'local' which needs to pass 
arguments ( 3/4 string arguments, containing whitespaces like spaces, etc ) to 
a python script, remote.py running on 'remote' (the remote machine).

I have the following questions:

1. What's the best way to accomplish my task ?
I have researched quite a bit & pretty much everybody is using ssh.
After googling a bunch, most people are using very complex workarounds to do 
this sort of thing. 

I googled & found people using several libraries to accomplish ssh to remote 
machine & execute a command on remote machine.
paramiko ( now forked into the ssh moduke), fabric, pushy ,etc

People who have used any of these libraries, which one would you recommend, as 
the most apt (simple & easy to use, lightweight, best performance, etc) for my 
situation ?

2. I would prefer a solution, which does NOT require the installation of extra 
libraries on the local & remote machines.
If installing external librar

3. Has anybody been able to do this using os.system ?

I tried this
>>> import os
>>> os.system ("ssh remoteuser@remote python remote.py arg1 arg2 arg3")

This worked, but if the arguments i tried to pass, had spaces, i was not able 
to 'escape' the spaces.

Any & all explanations/links/code 
snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor 
community would be greatly appreciated.

Thanks a ton

cheers
ashish

email : 
ashish.makani
domain:gmail.com

“The only way to do great work is to love what you do. If you haven’t found it 
yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know 
when you find it.” - Steve Jobs (1955 - 2011)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: 'indent'ing Python in windows bat

2012-09-19 Thread David Smith

On 2012-09-19 14:18, Terry Reedy wrote:

stating correctly that it works for exec().


My mistake. I fancied you were talking shell, not python. I now see that 
Python 3 has exec() as a built-in.


python -c "exec('print(\"hi\")\nif 0:\n print(\"hi\")\nelif 1:\n 
print(\"hi2\")')"

worked right off the *.bat. Shades of sed!
Note I used a one space indentation. A tab works fine, too.


python -c "exec('print(%1)\nif 1: print(2)')"
and calling 'tem 3' prints
3
2
Thanks for the exhaustive study. :-) I'll keep it in mind. I hope I 
don't have to do this, though.



That said, if you have many multiline statements, putting them in a
separate file or files may be a good idea.


ASAP I'm hoping to have each bat swallowed completely by python. My 
current "bathon" or "pytch" file closes an old session then opens the 
session I select just like the bat mom used to bake.


Thank you again, Terry, and thanks to all -- even the *nix'ers. Might 
come in handy if I get back into that again.


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


Re: Passing arguments to & executing, a python script on a remote machine from a python script on local machine (using ssh ?)

2012-09-19 Thread Ismael Farfán
2012/9/19 ashish :
> Hi c.l.p folks
>
> Here is my situation
>
> 1. I have two machines. Lets call them 'local' & 'remote'.
> Both run ubuntu & both have python installed
>
> 2. I have a python script, local.py, running on 'local' which needs to pass 
> arguments ( 3/4 string arguments, containing whitespaces like spaces, etc ) 
> to a python script, remote.py running on 'remote' (the remote machine).
>
> I have the following questions:
>
> 1. What's the best way to accomplish my task ?
> I have researched quite a bit & pretty much everybody is using ssh.
> After googling a bunch, most people are using very complex workarounds to do 
> this sort of thing.
>
> I googled & found people using several libraries to accomplish ssh to remote 
> machine & execute a command on remote machine.
> paramiko ( now forked into the ssh moduke), fabric, pushy ,etc
>
> People who have used any of these libraries, which one would you recommend, 
> as the most apt (simple & easy to use, lightweight, best performance, etc) 
> for my situation ?
>
> 2. I would prefer a solution, which does NOT require the installation of 
> extra libraries on the local & remote machines.
> If installing external librar
>
> 3. Has anybody been able to do this using os.system ?
>
> I tried this
 import os
 os.system ("ssh remoteuser@remote python remote.py arg1 arg2 arg3")
>
> This worked, but if the arguments i tried to pass, had spaces, i was not able 
> to 'escape' the spaces.

How about something like this:
os.system ( 'ssh remoteuser@remote python remote.py "arg 1" "arg 2" "arg 3"' )

Cheers
Ismael


>
> Any & all explanations/links/code 
> snippets/thoughts/ideas/suggestions/feedback/comments/ of the Python tutor 
> community would be greatly appreciated.
>
> Thanks a ton
>
> cheers
> ashish
>
> email :
> ashish.makani
> domain:gmail.com
>
> “The only way to do great work is to love what you do. If you haven’t found 
> it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll 
> know when you find it.” - Steve Jobs (1955 - 2011)
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
Do not let me induce you to satisfy my curiosity, from an expectation,
that I shall gratify yours. What I may judge proper to conceal, does
not concern myself alone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Ismael Farfán
2012/9/19 Ismael Farfán :
> Hello list
>
> From man 2 EXECVE
> "By default, file descriptors remain open across an execve()"
>
> And from man 2 FCNTL
> "Record locks are... preserved across an execve(2)."
>
> So the question:
> * If I execve a python script (from C), how can I retrieve the list of
> files, and optionally the list of locks, from within the execve(d)
> python process so that I can use them?
>
>
> Some more info:
> I'm working with exotic stuff like AIX and Solaris 10 (Windows and
> linux too :) and my lowest common denominator is python 2.3.
>
> From a standalone test within the interpreter I'd expect to get (at
> least) std(in/out/err).
>
> If more information is needed in order to help me, please let me know.
>
> Cheers
> Ismael
>
>
> --
> Do not let me induce you to satisfy my curiosity, from an expectation,
> that I shall gratify yours. What I may judge proper to conceal, does
> not concern myself alone.

It seems like I can use os.fstat to find out if a fd exists and also
get it's type and mode (I'm getting some pipes too : )

I hope it's portable across platforms, if someone knows a better
solution please let me know.

Ismael



-- 
Do not let me induce you to satisfy my curiosity, from an expectation,
that I shall gratify yours. What I may judge proper to conceal, does
not concern myself alone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Ian Kelly
On Wed, Sep 19, 2012 at 11:34 AM, Ismael Farfán  wrote:
> So the question:
> * If I execve a python script (from C), how can I retrieve the list of
> files, and optionally the list of locks, from within the execve(d)
> python process so that I can use them?
>
>
> Some more info:
> I'm working with exotic stuff like AIX and Solaris 10 (Windows and
> linux too :) and my lowest common denominator is python 2.3.

You could do:

os.listdir("/proc/%d/fd" % os.getpid())

This should work on Linux, AIX, and Solaris, but obviously not on Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Ian Kelly
On Wed, Sep 19, 2012 at 2:36 PM, Ismael Farfán  wrote:
> It seems like I can use os.fstat to find out if a fd exists and also
> get it's type and mode (I'm getting some pipes too : )

Sure, because files and pipes both use the file descriptor
abstraction.  If your process does any networking, you'll find sockets
in there as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Ismael Farfán
2012/9/19 Ian Kelly :
> On Wed, Sep 19, 2012 at 2:36 PM, Ismael Farfán  wrote:
>> It seems like I can use os.fstat to find out if a fd exists and also
>> get it's type and mode (I'm getting some pipes too : )
>
> Sure, because files and pipes both use the file descriptor
> abstraction.  If your process does any networking, you'll find sockets
> in there as well.
> --
> http://mail.python.org/mailman/listinfo/python-list

Seems like things will get interesting :D

Ismael


-- 
Do not let me induce you to satisfy my curiosity, from an expectation,
that I shall gratify yours. What I may judge proper to conceal, does
not concern myself alone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum works in sequences (Python 3)

2012-09-19 Thread Hans Mulder
On 19/09/12 17:07:04, Alister wrote:
> On Wed, 19 Sep 2012 16:41:20 +0200, Franck Ditter wrote:
> 
>> Hello,
>> I wonder why sum does not work on the string sequence in Python 3 :
>>
> sum((8,5,9,3))
>> 25
> sum([5,8,3,9,2])
>> 27
> sum('rtarze')
>> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>
>> I naively thought that sum('abc') would expand to 'a'+'b'+'c'
>> And the error message is somewhat cryptic...
>>
>> franck
> 
> Summation is a mathematical function that works on numbers
> Concatenation is the process of appending 1 string to another

Actually, the 'sum' builtin function is quite capable of
concatenatig objects, for example lists:

>>> sum(([2,3], [5,8], [13,21]), [])
[2, 3, 5, 8, 13, 21]

But if you pass a string as a starting value, you get an error:

>>> sum([], '')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: sum() can't sum strings [use ''.join(seq) instead]

In fact, you can bamboozle 'sum' into concatenating string by
by tricking it with a non-string starting value:

>>> class not_a_string(object):
...   def __add__(self, other):
... return other
...
>>> sum("rtarze", not_a_string())
'rtarze'
>>> sum(["Monty ", "Python", "'s Fly", "ing Ci", "rcus"],
... not_a_string())
"Monty Python's Flying Circus"
>>>


Hope this helps,

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


Re: Using dict as object

2012-09-19 Thread Oscar Benjamin
On 2012-09-19, Pierre Tardy  wrote:
> --===1362296571==
> Content-Type: multipart/alternative; boundary=bcaec554d3229e814204ca105e50
>
> --bcaec554d3229e814204ca105e50
> Content-Type: text/plain; charset=ISO-8859-1
>
>>
>>  This has been proposed and discussed and even implemented many
>> times on this list and others.
>>
> I can find this question on SO
> http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
> which is basically answered with this solution
>
> class AttributeDict(dict):
> __getattr__ = dict.__getitem__
> __setattr__ = dict.__setitem__
>
>
> but this does not allow recursive access, you would need to first convert
> all nested dictionaries to AttributeDict.
> a.b.c.d = 2 # fail
> a.b = dict(c=3)
> a.b.c=4 # fail

There is no way to control "recursive access" in Python. The statement

a.b.c = 2

is equivalent to the statements

o = a.b   # o = a.__getattr__('b')
o.c = 2   # o.__setattr__('c', 2)

The way that the o.c assignment is handled is determined by the type of o
regardless of the type of a. If you're looking for a way to change only the
type of a and make a custom __(set|get)attr__ work for all dicts that are
indirectly referred to then there is no solution to your problem.

Oscar

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


Re: How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Christian Heimes
Am 19.09.2012 19:34, schrieb Ismael Farfán:
> Hello list
> 
> From man 2 EXECVE
> "By default, file descriptors remain open across an execve()"
> 
> And from man 2 FCNTL
> "Record locks are... preserved across an execve(2)."
> 
> So the question:
> * If I execve a python script (from C), how can I retrieve the list of
> files, and optionally the list of locks, from within the execve(d)
> python process so that I can use them?

Have a look at psutil:

http://code.google.com/p/psutil/#Process_management

Christian

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


Installing Pip onto a mac os x system

2012-09-19 Thread John Mordecai Dildy
Does anyone know how to install Pip onto a mac os x ver 10.7.4?

Ive tried easy_instal pip but it brings up this message (but it doesn't help 
with my problem):

error: can't create or remove files in install directory

The following error occurred while trying to add or remove files in the
installation directory:

[Errno 13] Permission denied: 
'/Library/Python/2.7/site-packages/test-easy-install-1820.write-test'

The installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:

/Library/Python/2.7/site-packages/

Perhaps your account does not have write access to this directory?  If the
installation directory is a system-owned directory, you may need to sign in
as the administrator or "root" account.  If you do not have administrative
access to this machine, you may wish to choose a different installation
directory, preferably one that is listed in your PYTHONPATH environment
variable.

For information on other options, you may wish to consult the
documentation at:

  http://peak.telecommunity.com/EasyInstall.html

Please make the appropriate changes for your system and try again.

Thing is I am the Administrator of the computer and can use all of the folders 
on the mac computer.

Thank you in advance if you guys can help me with the problem,

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


Re: Installing Pip onto a mac os x system

2012-09-19 Thread Benjamin Kaplan
On Sep 19, 2012 6:37 PM, "John Mordecai Dildy"  wrote:
>
> Does anyone know how to install Pip onto a mac os x ver 10.7.4?
>
> Ive tried easy_instal pip but it brings up this message (but it doesn't
help with my problem):
>
> error: can't create or remove files in install directory
>
> The following error occurred while trying to add or remove files in the
> installation directory:
>
> [Errno 13] Permission denied:
'/Library/Python/2.7/site-packages/test-easy-install-1820.write-test'
>
> The installation directory you specified (via --install-dir, --prefix, or
> the distutils default setting) was:
>
> /Library/Python/2.7/site-packages/
>
> Perhaps your account does not have write access to this directory?  If the
> installation directory is a system-owned directory, you may need to sign
in
> as the administrator or "root" account.  If you do not have administrative
> access to this machine, you may wish to choose a different installation
> directory, preferably one that is listed in your PYTHONPATH environment
> variable.
>
> For information on other options, you may wish to consult the
> documentation at:
>
>   http://peak.telecommunity.com/EasyInstall.html
>
> Please make the appropriate changes for your system and try again.
>
> Thing is I am the Administrator of the computer and can use all of the
folders on the mac computer.
>

No you can't. You can ask permission to use skill the folders (and then
grant yourself that permission), but the user that you're currently running
as does not have full access to the computer.

You know how every time you install a program, a prompt comes up asking for
your password? That's you giving the process permission to run as "root",
the only account with full access to everything.

On the command line, you run things as root by using the "sudo" command
(being an administrator means your account is able to run that)

sudo easy_install pip

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


Re: How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Chris Angelico
On Thu, Sep 20, 2012 at 7:09 AM, Ian Kelly  wrote:
> You could do:
>
> os.listdir("/proc/%d/fd" % os.getpid())
>
> This should work on Linux, AIX, and Solaris, but obviously not on Windows.

I'm not sure how cross-platform it is, but at least on Linux, you can
use /proc/self as an alias for "/proc/"+os.getpid() - worth a try,
might make your code a bit easier to read.

It's documented as useful when you don't know the PID yet (eg telling
a process to read the file /proc/self/fd/0 to force it to use stdin).
So I'm confident enough to recommend testing it. :)

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


Re: Programming Issues

2012-09-19 Thread Jason Friedman
> Ask the user for the amount of change expressed in cents. Your program must
> compute and display the number of half-dollars, quarters, dimes, nickels,
> and pennies to be returned.
> Return as many half-dollars as possible, then quarters, dimes, nickels, and
> pennies, in that order.
> Your program must allow the user to continue entering different amounts of
> change until they enter 0 to indicate they are finished. If the user enters
> a negative number, inform them of their mistake and ask them to enter a
> correct value.

Perhaps you can start with pseudo-code
(http://en.wikipedia.org/wiki/Pseudo_code) and ask for help writing
that in Python.  I'll get you started.

Ask for a number.
If number = 0, stop.
If number < 0, ask again.

With values 50, 25, 10, 5 and 1:
if number > value:
coincount = integer portion of number divided by value
print coincount, value
remaining number = ...

I've broken the pseudo-code into two parts because they are, in some
sense, different programs.
You might try to write one, then the other.
In other words, starting by writing this in Python:

Ask for a number.
If number = 0, stop.
If number < 0, ask again.
If number > 0, print number and quit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing arguments to & executing, a python script on a remote machine from a python script on local machine (using ssh ?)

2012-09-19 Thread Tim Roberts
ashish  wrote:
>
>Here is my situation
>
>1. I have two machines. Lets call them 'local' & 'remote'.
>Both run ubuntu & both have python installed
>
>2. I have a python script, local.py, running on 'local' which needs to pass
>arguments ( 3/4 string arguments, containing whitespaces like spaces, etc )
>to a python script, remote.py running on 'remote' (the remote machine).

You haven't provided very many details, so it's possible ssh is the
low-impact solution, but don't discard the possibility of using a TCP
socket for this.  It's easy in Python.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get the list of all my open file(descriptor)s and locks?

2012-09-19 Thread Ismael Farfán
2012/9/19 Christian Heimes :
>> So the question:
>> * If I execve a python script (from C), how can I retrieve the list of
>> files, and optionally the list of locks, from within the execve(d)
>> python process so that I can use them?
>
> Have a look at psutil:
>
> http://code.google.com/p/psutil/#Process_management
>
> Christian
>
> --
> http://mail.python.org/mailman/listinfo/python-list

Unfortunately  I'm not allowed to install 3rd party SW unless it's
absolutely necessary, but thanks for sharing, I'll have a look at the
arch dependent code : )

Ismael


-- 
Do not let me induce you to satisfy my curiosity, from an expectation,
that I shall gratify yours. What I may judge proper to conceal, does
not concern myself alone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing arguments to & executing, a python script on a remote machine from a python script on local machine

2012-09-19 Thread Steven D'Aprano
On Wed, 19 Sep 2012 12:46:33 -0700, ashish wrote:

> Hi PyTutor Folks
> 
> Here is my situation
> 
> 1. I have two machines. Lets call them local & remote. Both run ubuntu &
> both have python installed
> 
> 2. I have a python script, local.py, running on local which needs to
> pass arguments ( 3/4 string arguments, containing whitespaces like
> spaces, etc ) to a python script, remote.py running on remote (the
> remote machine).

If 3/4 of the arguments are strings, what sort of objects are the other 
1/4?


> I have the following questions:
> 
> 1. What's the best way to accomplish my task ? 

Use a dedicated remote procedure call library. Do not try to invent your 
own. The wheel has already been invented, you are just wasting your time.

I've used both Pyro and Rpyc, either of them seem perfectly reasonable. 
There are many others, but frankly I don't think there is a "best of 
breed" that stands far ahead of the rest.



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


Re: Passing arguments to & executing, a python script on a remote machine from a python script on local machine

2012-09-19 Thread Chris Angelico
On Thu, Sep 20, 2012 at 2:27 PM, Steven D'Aprano
 wrote:
> On Wed, 19 Sep 2012 12:46:33 -0700, ashish wrote:
>
>> 2. I have a python script, local.py, running on local which needs to
>> pass arguments ( 3/4 string arguments, containing whitespaces like
>> spaces, etc ) to a python script, remote.py running on remote (the
>> remote machine).
>
> If 3/4 of the arguments are strings, what sort of objects are the other
> 1/4?

I understand the OP as meaning "three or four string arguments".

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


Re: using text file to get ip address from hostname

2012-09-19 Thread Dan Katorza
בתאריך יום רביעי, 19 בספטמבר 2012 15:28:23 UTC+3, מאת Dan Katorza:
> בתאריך יום רביעי, 19 בספטמבר 2012 12:11:04 UTC+3, מאת Dan Katorza:
> 
> > בתאריך יום רביעי, 19 בספטמבר 2012 11:50:56 UTC+3, מאת Dan Katorza:
> 
> > 
> 
> > > בתאריך יום רביעי, 19 בספטמבר 2012 11:14:29 UTC+3, מאת Chris Angelico:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > On Wed, Sep 19, 2012 at 5:41 PM, Dan Katorza  wrote:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > >
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > > Hello again,
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > > I have another question and i hope you will understand me..
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > > Is there any option where you can set the program to go back to lets 
> > > > > say the top of the code?
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > > I mean if the program finished the operation and i want to stay in 
> > > > > the program and go back ro the start.
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > > after any operation i want the option to do it again , go back to the 
> > > > > main menu or full exit from the program, and i want it every time.
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > >
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > > i hope i'm clear :)
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > Yep! Look up the docs and tutorial on "control flow" and "looping
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > constructs". Sounds like what you want here is a 'while' loop.
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > > ChrisA
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > Hi Chris,
> 
> > 
> 
> > > 
> 
> > 
> 
> > > this is my code:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > #!/usr/bin/env python
> 
> > 
> 
> > > 
> 
> > 
> 
> > > #Get the IP Address
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > import sys, socket
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print ("\n\n#")
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print ("#Get IP from Host v 1.0 #")
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print ("#")
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print ("# Choose from the options below #")
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print ("#  1- url , 2-File(Text file only.txt)  #")
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print ("#\n")
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > mchoice = int(raw_input("Please enter your choice> "))
> 
> > 
> 
> > > 
> 
> > 
> 
> > > while mchoice !=1 and  mchoice !=2:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print("{0} is not a menu option.".format(mchoice))
> 
> > 
> 
> > > 
> 
> > 
> 
> > > mchoice = int(raw_input("Please try again> "))
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > if mchoice == 2:
> 
> > 
> 
> > > 
> 
> > 
> 
> > >   filename = raw_input("Hello, please enter file name here> ")
> 
> > 
> 
> > > 
> 
> > 
> 
> > >   if filename.endswith(".txt"):
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > >try:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > infile = open(filename)
> 
> > 
> 
> > > 
> 
> > 
> 
> > >except EnvironmentError as e:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print(e)
> 
> > 
> 
> > > 
> 
> > 
> 
> > > sys.exit(1)
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > > 
> 
> > 
> 
> > >print("\nFile {0} exists!".format(filename))
> 
> > 
> 
> > > 
> 
> > 
> 
> > >print("\nGetting IP addresses for hosts")
> 
> > 
> 
> > > 
> 
> > 
> 
> > >print("\n")
> 
> > 
> 
> > > 
> 
> > 
> 
> > >   else:
> 
> > 
> 
> > > 
> 
> > 
> 
> > >print("{0} is not a Text file.".format(filename))
> 
> > 
> 
> > > 
> 
> > 
> 
> > >sys.exit(1)
> 
> > 
> 
> > > 
> 
> > 
> 
> > >   for line in infile:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > hostname = line.strip()
> 
> > 
> 
> > > 
> 
> > 
> 
> > > try:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > ip_address = socket.gethostbyname(hostname)
> 
> > 
> 
> > > 
> 
> > 
> 
> > > except EnvironmentError as e:
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print("Couldn't find IP address for {0}: {1}".format(hostname, e))
> 
> > 
> 
> > > 
> 
> > 
> 
> > > continue
> 
> > 
> 
> > > 
> 
> > 
> 
> > > print("IP address for {0} is {1}.".format(hostname, ip_addre