Function passed as an argument returns none

2014-10-01 Thread Shiva
Hi,
I am learning Python (version 3.4) strings.I have a function that takes in a
parameter and prints it out as given below.

def donuts(count):
  if count <= 5:
print('Number of donuts: ',count)
  else:
print('Number of donuts: many')
return

It works fine if I call 
donuts(5)

It returns:
we have 5 DN  (as expected)

However if I do :

test(donuts(4), 'Number of donuts: 4')


where test is defined as below:

def test(got, expected):
  print('got: ', got, 'Expected:' ,expected)
  if got == expected:
prefix = ' OK '
  else:
prefix = '  X '
  print (('%s got: %s expected: %s') % (prefix, repr(got), repr(expected)))


Only 'None' gets passed on to parameter 'got' instead of the expected value
of 4.
Any idea why 'None' is getting passed even though calling the donuts(4)
alone returns the expected value?

Thanks,
Shiva.

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


Re: Function passed as an argument returns none

2014-10-02 Thread Shiva
Hi All,

Thank you everyone. This is fantastic - I post a query and go to sleep and
by the time I get up there is already a nice little thread of discussion
going on.

By the way, I sorted it with all your suggestions.

def donuts(count):
  if count <= 9: #This had to be 9 instead of 5 as per the question req.
return 'Number of donuts: {0}'.format(count)
  else:
return 'Number of donuts: many'

So to summarise what I learnt:

* Just 'return' returns None - it is not related to what you print inside
the function.If you want something specific out of a function return
something specific.

* return 'Number of donuts: ',countreturns a tuple like:
('Number of donuts: ',9)

* To just print the string without returning it as tuple , use string
formatting.

Thanks again,
Shiva

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


Returning a List

2014-10-03 Thread Shiva
Hi All,

I might be doing something really silly here, but I can't seem to spot it:

def front_x(words):
  b=[]
  c=[]
  for a in words:
 if a[0] == 'x':
 b.append(a)
 else:
 c.append(a)

  b = sorted(b)
  c = sorted(c)
  d= b+c
  print('d = ',d)

  #return b+c
  return d

front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])



Why is return d or return b+c not returning anything??

The d's value is confirmed by the print statement.

Thanks,
Shiva.

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


Re: Returning a List

2014-10-03 Thread Shiva
Chris Angelico  gmail.com> writes:

> 
> On Fri, Oct 3, 2014 at 9:35 PM, Shiva
>  yahoo.com.dmarc.invalid> wrote:
> > Why is return d or return b+c not returning anything??
> >
> 
> On what basis do you believe it's not returning anything? When you
> call it, down below, you're ignoring its return value. I expect it's
> returning just fine, but you then do nothing with it.
> 
> ChrisA
> 


I wrongly thought calling the function was enough. Looks like the call is
just a placeholder for the returned value. Need to print it out.

Thanks!!

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


Issue in printing top 20 dictionary items by dictionary value

2014-10-04 Thread Shiva
Hi All,

I have written a function that 
-reads a file 
-splits the words and stores it in a dictionary as word(key) and the total
count of word in file (value).

I want to print the words with top 20 occurrences in the file in reverse
order - but can't figure it out. Here is my function:

def print_top(filename):

#Open a file
path = '/home/BCA/Documents/LearnPython/ic/'
fname = path + filename
print ('filename: ',fname)
filetext = open(fname)

#Read the file
textstorage={}

#print(type(textstorage))
readall = filetext.read().lower()
eachword = set(readall.split())

#store split words as keys in dictionary
for w in eachword:
textstorage[w] = readall.count(w)

#print top 20 items in dictionary by decending order of val
# This bit is what I can't figure out.

for dkey in (textstorage.keys()):
print(dkey,sorted(textstorage[dkey]))??
   

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


Re: Issue in printing top 20 dictionary items by dictionary value

2014-10-04 Thread Shiva
It works :
orderedwords = sorted(textstorage.keys(), key=textstorage.get)

The method textstorage.get will accept a word and return it's value which in
this instance is the count.

What I don't understand is:

for w in eachword:
textstorage[w]=textstorage.get(w, 0) + 1

How does textstorage.get(w,0)+1 give the count of the word??

Thanks,
Shiva

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


Re: Issue in printing top 20 dictionary items by dictionary value

2014-10-05 Thread Shiva
Larry Hudson  yahoo.com.dmarc.invalid> writes:

> 
> On 10/04/2014 10:36 AM, Shiva wrote:
> >
> > What I don't understand is:
> >
> >  for w in eachword:
> >  textstorage[w]=textstorage.get(w, 0) + 1
> >
> > How does textstorage.get(w,0)+1 give the count of the word??
> >
> 
> Very long-winded explanation:  (But to shorten it a bit, I'm going to use
ts in place of 
> textstorage.  Also lhs = left-hand-side and rhs = right-hand-side.)
> 
> What we're trying to do here is to update the word count.  We could
(erroneously) write it as:
> 
> ts[w] = ts[w] + 1
> 
> If w already exists in the ts dictionary, this works fine.  But if it does
not it will abort 
> with a KeyError when it comes to the ts[w] on the rhs of the assignment.
> 
> The get() method is an alternate way of accessing the value of a key in a
dictionary, but with a 
> default value given as well.  Now let's break down the statement
> 
> ts[w] = ts.get(w, 0) + 1
> 
> Case 1:  w already exists in the ts dictionary:
> 
> ts.get(w, 0) gets the value of ts[w] (the current word count), adds 1,
which is then used to 
> update the word-count value of ts[w] (on the lhs of the assignment).
> 
> case2:  w does not exist in the ts dictionary:
> 
> ts.get(w, 0) gives the default value of 0, and 1 is added to that.  ts[w]
on the lhs of the 
> assignment does not exist, so a new entry is created in the ts dictionary
with the given w as 
> the key, and the value is initialized with the 1 from the get()+1.
> 
> Make sense?
> 
>   -=- Larry -=-
> 
> 

Hi Larry,

Thanks for the explanation - I was a bit confused as get() operation in this
case would have got None for words occurring the first time.
Now I understand by writing a small example in the interpreter:

>>> dt={}
>>> splitw=('aa','bb','cc')
>>> for w in splitw:
... dt[w]=dt.get(w,0)
... 
>>> dt
{'cc': 0, 'bb': 0, 'aa': 0}

So we just increment 0 to 1 for count.

Thanks,
Pradeep




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


re search through a text Vs line

2014-10-05 Thread Shiva
Hi,

I am doing a regular expression search for a year through a file.

  fileextract = open(fullfilename,'r')
  line = fileextract.read()
  texts = re.search(r'1\d\d\d', line)
  print(texts.group())

The above works.

However if I do:
 fileextract = open(fullfilename,'r')
 line = fileextract.readlines()

 for l in line:
texts = re.search(r'1\d\d\d', line)
 print(texts.group())


None is returned. Why is it not iterating through each line of the file and
doing a search? - It seems to return none.

Thanks,
Shiva

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


Re: re search through a text Vs line

2014-10-05 Thread Shiva
OK,
Hi Dave,

I modified it as below and it works(If there is a way to make this more
efficient please let me know)

By the way I am using Python 3.4

import sys
import re


def extract_names(filename):

  path = '/home/LearnPython/exercises/'
  fullfilename = path+filename
  print('fullfilename: ',fullfilename)

  fileextract = open(fullfilename,'r')
  #line = fileextract.readlines()
  #print(line)
  for l in fileextract:
#print(l)
texts = re.search(r'\d\d\d\d', l)
if texts:
  print(texts.group())


#print(texts.group())

  #return texts.group()
  fileextract.close()



extract_names('NOTICE.txt')

Thanks,
Shiva

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


while loop - multiple condition

2014-10-12 Thread Shiva
Why is the second part of while condition not being checked?

while ans.lower() != 'yes' or ans.lower()[0] != 'y':
 ans = input('Do you like python?')


My intention is if either of the conditions are true the loop should break.
But the condition after 'or' doesn't seem to evaluate.

Thanks,
Shiva.

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


Re: while loop - multiple condition

2014-10-12 Thread Shiva

> The loop will continue while either part is true - that's what "or"
> means. Is that what you intended it to be doing?
> 
> ChrisA
> 


Yes..however, the second part of the or condition doesn't get evaluated.
So if I enter a 'y' - I expect the second part to evaluate and the loop to
break - but that doesn't seem to happen.

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


Re: while loop - multiple condition

2014-10-12 Thread Shiva
Bit confusing to use in While loop - Should have used the 'and' condition
instead of OR- then it works fine.
for OR both condition need to be false to produce a false output and break
the loop.
More of SET operations.

Thanks,
Shiva

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


downloading from links within a webpage

2014-10-14 Thread Shiva
Hi,

Here is a small code that I wrote that downloads images from a webpage url
specified (you can limit to how many downloads you want). However, I am
looking at adding functionality and searching external links from this page
and downloading the same number of images from that page as well.(And
limiting the depth it can go to)

Any ideas?  (I am using Python 3.4 & I am a beginner)

import urllib.request
import re
url="http://www.abc.com";

pagehtml = urllib.request.urlopen(url)
myfile = pagehtml.read()
matches=re.findall(r'http://\S+jpg|jpeg',str(myfile))


for urltodownload in matches[0:50]:
  imagename=urltodownload[-12:]
  urllib.request.urlretrieve(urltodownload,imagename)

print('Done!')
 
Thanks,
Shiva

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


Creating a counter

2014-10-15 Thread Shiva
Hi,

I am trying to search a string through files in a directory - however while
Python script works on it and writes a log - I want to present the user with
count of number of strings found. So it should increment for each string found.

How do I implement it?

If I use a print() within a if condition statement - and execute the script
in terminal - for each find, the print() prints in new line instead of a
constantly incrementing counter.

Thanks,
Shiva

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


Re: Creating a counter

2014-10-16 Thread Shiva

> 
> Python3:
>print(counter, end='\r')
> 
> Gary Herron
> 
> 


Thanks, that is what I was looking up - \r carriage return without linefeed.

Thanks again!
Shiva

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


The difference sports gambling online sport book

2008-10-05 Thread shiva
webpage -  http;//elemotor.blogspot.com/




The difference sports gambling online sport book


The difference sports gambling online sport book no doubt partly
sports gambling
online sport book to the fact sports gambling online sport book our
first
glimpses sports gambling online sport book of Hellenic and of sports
gambling
--
http://mail.python.org/mailman/listinfo/python-list


Create notifications in python

2016-01-13 Thread Shiva Upreti
I want to create notification box using python just like I get when battery is 
running low or something similar. I can do it using libnotify in linux, but I 
cant figure out how to do it in windows. I got some codes on internet for this 
like:
https://gist.github.com/wontoncc/1808234, however it didnt work on windows 10. 
It showed the notification icon but nothing else happened. I cant understand 
this code as well.
I would like to ask you how to achieve the above, and what should I learn so 
that I am able to understand what the code above does and learn to write it 
myself. Please provide learning sources if you can, because I cant understand 
any of it so I dont even know from where to begin.

Any help will be highly appreciated.:)
-- 
https://mail.python.org/mailman/listinfo/python-list


wxpython strange behaviour

2016-01-15 Thread Shiva Upreti
https://gist.github.com/anonymous/4baa67aafd04555eb4e6

I wrote the above code to display a toasterbox, and I didnt want it to display 
any frames on the screen, just a toasterbox. The problem with this code is that 
it runs fine when I run it the first time, but when I run it next time it shows 
some error and the toasterbox doesnt disappear from the screen itself(it should 
though).
Error message I got:
https://gist.github.com/anonymous/f0d4ec685d2432c80a1

There is one more issue. I am using canopy as my environment, and when i run it 
using canopy it works fine at least for the first time but when I run it using 
command prompt in windows 10, nothing happens, I get no errors and still it 
does not work.

Please help me solve these issues.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: wxpython strange behaviour

2016-01-15 Thread Shiva Upreti
On Friday, January 15, 2016 at 10:35:57 PM UTC+5:30, Shiva Upreti wrote:
> https://gist.github.com/anonymous/4baa67aafd04555eb4e6
> 
> I wrote the above code to display a toasterbox, and I didnt want it to 
> display any frames on the screen, just a toasterbox. The problem with this 
> code is that it runs fine when I run it the first time, but when I run it 
> next time it shows some error and the toasterbox doesnt disappear from the 
> screen itself(it should though).
> Error message I got:
> https://gist.github.com/anonymous/f0d4ec685d2432c80a1
> 
> There is one more issue. I am using canopy as my environment, and when i run 
> it using canopy it works fine at least for the first time but when I run it 
> using command prompt in windows 10, nothing happens, I get no errors and 
> still it does not work.
> 
> Please help me solve these issues.

New link to error message, old one is giving 404:
http://pasted.co/f398a1e4
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: wxpython strange behaviour

2016-01-15 Thread Shiva Upreti
On Friday, January 15, 2016 at 10:55:59 PM UTC+5:30, Ian wrote:
> On Fri, Jan 15, 2016 at 10:05 AM, Shiva Upreti  
> wrote:
> > https://gist.github.com/anonymous/4baa67aafd04555eb4e6
> >
> > I wrote the above code to display a toasterbox, and I didnt want it to 
> > display any frames on the screen, just a toasterbox. The problem with this 
> > code is that it runs fine when I run it the first time, but when I run it 
> > next time it shows some error and the toasterbox doesnt disappear from the 
> > screen itself(it should though).
> > Error message I got:
> > https://gist.github.com/anonymous/f0d4ec685d2432c80a1
> 
> The first gist is short enough that it easily could have been included
> inline in your message. The second gist is a 404 (looks like it may be
> short one hex digit).
> 
> I haven't used wxPython in a while and I've never used that ToasterBox
> widget, but I'll see what I can answer.
> 
> If you don't want any frames then you should probably use parent=None,
> not parent=wx.Frame(None), which creates a frame. Also, the purpose of
> the panel is unclear since it's never used.
> 
> When you say that you run it the next time, do you mean that you're
> running this script twice, as two separate processes, and getting
> different results? That seems strange. Or do you mean that you're
> invoking this code multiple times in the same Python process?

parent=None doesnt work, it gives error:

AttributeErrorTraceback (most recent call last)
C:\Users\Mike\Desktop\zz.py in ()
  5 app = wx.App()
  6 panel=wx.Panel(parent=wx.Frame(None))
> 7 toaster = TB.ToasterBox(parent=None, tbstyle=TB.TB_COMPLEX, 
closingstyle=TB.TB_ONTIME)
  8 
  9 toaster.SetPopupPauseTime(3000)

C:\Users\Mike\AppData\Local\Enthought\Canopy\User\lib\site-packages\wx\lib\agw\toasterbox.pyc
 in __init__(self, parent, tbstyle, windowstyle, closingstyle, scrollType)
135 wx.GetDisplaySize().GetHeight())
136 
--> 137parent.Bind(wx.EVT_ICONIZE, lambda evt: [w.Hide() for w in 
winlist])
138 
139self._tb = ToasterBoxWindow(self._parent, self, self._tbstyle, 
self._windowstyle,

AttributeError: 'NoneType' object has no attribute 'Bind'

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


Re: wxpython strange behaviour

2016-01-15 Thread Shiva Upreti
On Friday, January 15, 2016 at 10:55:59 PM UTC+5:30, Ian wrote:
> On Fri, Jan 15, 2016 at 10:05 AM, Shiva Upreti  
> wrote:
> > https://gist.github.com/anonymous/4baa67aafd04555eb4e6
> >
> > I wrote the above code to display a toasterbox, and I didnt want it to 
> > display any frames on the screen, just a toasterbox. The problem with this 
> > code is that it runs fine when I run it the first time, but when I run it 
> > next time it shows some error and the toasterbox doesnt disappear from the 
> > screen itself(it should though).
> > Error message I got:
> > https://gist.github.com/anonymous/f0d4ec685d2432c80a1
> 
> The first gist is short enough that it easily could have been included
> inline in your message. The second gist is a 404 (looks like it may be
> short one hex digit).
> 
> I haven't used wxPython in a while and I've never used that ToasterBox
> widget, but I'll see what I can answer.
> 
> If you don't want any frames then you should probably use parent=None,
> not parent=wx.Frame(None), which creates a frame. Also, the purpose of
> the panel is unclear since it's never used.
> 
> When you say that you run it the next time, do you mean that you're
> running this script twice, as two separate processes, and getting
> different results? That seems strange. Or do you mean that you're
> invoking this code multiple times in the same Python process?

parent=None doesnt work, it gives error:



AttributeErrorTraceback (most recent call last)
C:\Users\Mike\Desktop\zz.py in ()
  5 app = wx.App()
  6 panel=wx.Panel(parent=wx.Frame(None))
> 7 toaster = TB.ToasterBox(parent=None, tbstyle=TB.TB_COMPLEX, 
closingstyle=TB.TB_ONTIME)
  8 
  9 toaster.SetPopupPauseTime(3000)

C:\Users\Mike\AppData\Local\Enthought\Canopy\User\lib\site-packages\wx\lib\agw\toasterbox.pyc
 in __init__(self, parent, tbstyle, windowstyle, closingstyle, scrollType)
135 wx.GetDisplaySize().GetHeight())
136 
--> 137parent.Bind(wx.EVT_ICONIZE, lambda evt: [w.Hide() for w in 
winlist])
138 
139self._tb = ToasterBoxWindow(self._parent, self, self._tbstyle, 
self._windowstyle,

AttributeError: 'NoneType' object has no attribute 'Bind'


By running it the next time I meant that I am running this script twice as 
separate processes and I run it the second time only after first process has 
finished its execution.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: wxpython strange behaviour

2016-01-15 Thread Shiva Upreti
On Saturday, January 16, 2016 at 2:22:24 AM UTC+5:30, Mark Lawrence wrote:
> On 15/01/2016 17:05, Shiva Upreti wrote:
> > https://gist.github.com/anonymous/4baa67aafd04555eb4e6
> >
> > I wrote the above code to display a toasterbox, and I didnt want it to 
> > display any frames on the screen, just a toasterbox. The problem with this 
> > code is that it runs fine when I run it the first time, but when I run it 
> > next time it shows some error and the toasterbox doesnt disappear from the 
> > screen itself(it should though).
> > Error message I got:
> > https://gist.github.com/anonymous/f0d4ec685d2432c80a1
> 
> I'm sorry that I can't help directly but you're more likely to get 
> answers here gmane.comp.python.wxpython.
> 
> >
> > There is one more issue. I am using canopy as my environment, and when i 
> > run it using canopy it works fine at least for the first time but when I 
> > run it using command prompt in windows 10, nothing happens, I get no errors 
> > and still it does not work.
> >
> 
> Two problems, one is that Canopy is *NOT* main stream Python, it is part 
> of the Enthought distibution, second is that "still it does not work" 
> amongst other things is about as much use as a wet fart in a 
> thunderstorm.  Please give us data that we can work with.
> 
> > Please help me solve these issues.
> >
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
> 
> Mark Lawrence

What kind of further details do you want? Please tell me and i will try my best 
to provide them.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: wxpython strange behaviour

2016-01-15 Thread Shiva Upreti
On Saturday, January 16, 2016 at 4:39:12 AM UTC+5:30, Dietmar Schwertberger 
wrote:
> On 15.01.2016 18:05, Shiva Upreti wrote:
> > Please help me solve these issues.
> Please decide first on which list or forum you want your questions to be 
> answered. Once people find out that you are asking the same questions 
> all over, the support will soon end.
> 
> Regards,
> 
> Dietmar

I am sorry, I didnt know about this. I will keep this in mind. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list



Pyaudio and sockets

2016-03-28 Thread Shiva Upreti
I am trying to send audio using sockets to a different PC, but audio is not 
clear on the other end and I cant understand why.

Here is the code:

import socket
import pyaudio
import wave
import sys
import pickle
import time

HOST=""
PORT=1061
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 3


def record(sock):   
def callback_record(in_data, frame_count, time_info, status):
#print len(in_data)
sock.sendall(in_data)   

return (in_data, pyaudio.paContinue)

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=False,
stream_callback=callback_record)

stream.start_stream()
return stream   


def play(sock):
def callback_play(in_data, frame_count, time_info, status):
#msg=recv_all(sock)
in_data=sock.recv(5000)
return (in_data, pyaudio.paContinue)

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=False,
output=True,
stream_callback=callback_play)

stream.start_stream()
return stream

def recv_all(sock):
data=sock.recv(5000)
return data


if sys.argv[1] == 'server':
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(10)
while(True):
print "Listening at:", s.getsockname()
sc, addr=s.accept()
print "Connection established with:", addr

while True:
stream_record=record(sc)
#stream_play=play(sc)
while stream_record.is_active():
#time.sleep(0.0)
pass
#stream_record.stop_stream()
#stream_record.close()
#stream_play.stop_stream()
#stream_play.close()

elif sys.argv[1]=='client':
s.connect((HOST, PORT))
while True: 
stream_play=play(s)
#time.sleep(5)
#stream_record=record(s)

while stream_play.is_active():
#time.sleep(0.0)
pass

#stream_record.stop_stream()
#stream_record.close()
#stream_play.stop_stream()
#stream_play.close()

To run it as server enter this command: 
python audio_chat2.py server
To run it as client enter this command: 
python audio_chat2.py client

I also tried running them on same PC, still voice was not clear.


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


"no module named kivy" import error in ubuntu 14.04

2015-08-16 Thread shiva upreti
Hi
I am new to linux. I tried various things in attempt to install kivy. I 
installed python 2.7.10 (I think python3 was already installed in ubuntu 
14.04). Then i downloaded kivy from 
https://pypi.python.org/packages/source/K/Kivy/Kivy-1.9.0.tar.gz, extracted it 
and tried to execute "python setup.py" inside the kivy folder. But it showed 
the error "no module named cython". Then I tried installing cython, it 
installed successfully but the command "python setup.py" still gave the error 
"no module named cython".
Finally I installed kivy using instructions on this video: 
https://www.youtube.com/watch?v=mypVFCIIZtw. Now when i try to run the 
following commands:

"$ cd  (I used the actual path, i.e., 
"/usr/share/kivy-examples")
 $ cd demo/touchtracer
 $ python main.py"
I am still getting the error:"ImportError: No module named kivy".

Any help will be highly appreciated.
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Selenium

2015-09-14 Thread shiva upreti
I wrote this code in python for submitting a login form:


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()

driver.get('some url')

elem = driver.find_element_by_name("username")
elem.send_keys('13103666')
elem = driver.find_element_by_name("password")
elem.send_keys('as')
driver.find_element_by_name("btnSubmit").click()
#nothing happens from here
print driver.page_source
print "test"


After clicking on submit button, a message is displayed on the same page 
whether login was successful or not. 
However after clicking on submit button, I lose control over the web page. I 
can't use any selenium functions now like 'driver.find_element_by_name()'.

Initially everything works fine. I can enter username and password using 
selenium as written in my code, but once I click on submit button or press 
return key(tried both using selenium), any script written after that(involving 
web driver) doesnt seem to work. Even driver.close() doesnt work.
This is the form I am trying to submit:


The submission is successful, however after submission I cant verify if login 
was successful or not because of the issue I posted above.
Do I need to switch web handle? If, then how.

Any help will be highly appreciated.
-- 
https://mail.python.org/mailman/listinfo/python-list


need help with selenium

2015-09-14 Thread shiva upreti
I wrote this code in python for submitting a login form: 

 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
driver = webdriver.Firefox() 

driver.get('some url') 

elem = driver.find_element_by_name("username") 
elem.send_keys('13103666') 
elem = driver.find_element_by_name("password") 
elem.send_keys('as') 
driver.find_element_by_name("btnSubmit").click() 
#nothing happens from here 
print driver.page_source 
print "test" 
 

After clicking on submit button, a message is displayed on the same page 
whether login was successful or not. 
However after clicking on submit button, I lose control over the web page. I 
can't use any selenium functions now like 'driver.find_element_by_name()'. 

Initially everything works fine. I can enter username and password using 
selenium as written in my code, but once I click on submit button or press 
return key(tried both using selenium), any script written after that(involving 
web driver) doesnt seem to work. Even driver.close() doesnt work. 
This is the form I am trying to submit: 
 

The submission is successful, however after submission I cant verify if login 
was successful or not because of the issue I posted above. 
Do I need to switch web handle? If, then how. 

Any help will be highly appreciated. 
-- 
https://mail.python.org/mailman/listinfo/python-list


ConnectionError handling problem

2015-09-18 Thread shiva upreti
I am learning python. I wrote a script using requests module.
The scripts runs fine for sometime, but after a while it hangs. When I press 
CTRL+C it shows ConnectionError even though I have included exception handling.
I am not sure as to why it cant handle ConnectionError when the script runs for 
a long time.

This is a part(causing issues) of the script I am running:

while(k<46656):
j=res[k]
url="http://172.16.68.6:8090/login.xml"; 
query_args = {'mode':'191', 'username':str(i), 
'password':str(j), 'a':'1442397582010', 'producttype':'0'}

try:
r=requests.post(url, data=query_args)
except:
print "Connection error"
time.sleep(30)
continue

html=r.text
if(len(html) < 10):
continue

if("The system could not log you on" not in html):
print "hello"
filehandle=open("ids", "a")
filehandle.write(str(i)+'\n')
filehandle.write(str(j)+'\n')
filehandle.close()
break

k=k+1

Any help will be highly appreciated.
-- 
https://mail.python.org/mailman/listinfo/python-list


for loop

2015-09-20 Thread shiva upreti
https://ideone.com/BPflPk

Please tell me why 'print s' statement is being executed inside loop, though I 
put it outside.
Please help. I am new to python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for loop

2015-09-20 Thread shiva upreti
On Sunday, September 20, 2015 at 1:33:57 PM UTC+5:30, Chris Warrick wrote:
> On 20 September 2015 at 09:55, shiva upreti  wrote:
> > https://ideone.com/BPflPk
> >
> > Please tell me why 'print s' statement is being executed inside loop, 
> > though I put it outside.
> > Please help. I am new to python.
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> 
> You have mixed indentation. Your code contains both tabs and spaces.
> Python interprets tabs as 8 spaces, while your other indentation is 4
> spaces, leading to bad parsing.
> 
> Please make sure you use only spaces (reconfigure your editor to
> always insert 4 spaces and reindent everything with tabs)
> 
> -- 
> Chris Warrick <https://chriswarrick.com/>
> PGP: 5EAAEA16

Thanks. It works fine now.:)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for loop

2015-09-20 Thread shiva upreti
On Sunday, September 20, 2015 at 1:34:32 PM UTC+5:30, paul.ant...@gmail.com 
wrote:
> On Sunday, September 20, 2015 at 9:56:06 AM UTC+2, shiva upreti wrote:
> > https://ideone.com/BPflPk
> > 
> > Please tell me why 'print s' statement is being executed inside loop, 
> > though I put it outside.
> > Please help. I am new to python.
> 
> Hi!
> 
> Welcome to python, the most awesome programming language!
> 
> The code you pasted used both spaces and tabs for indentation. The thing is 
> that python, by default, interprets one tab character as 8 spaces, but the 
> editor you've used shows it as 4 spaces. To avoid these kinds of headaches, I 
> always 1) set my editor to show tabs, so I can detect them, and 2) never use 
> tabs when I write code myself. I set my editor to insert 4 spaces whenever I 
> hit the "tab" key on my keyboard. If you post the name of your editor, maybe 
> someone knows how to do that in yours. You can also detect mixed space/tab 
> issues by running "python -t" instead of just "python".
> 
> So, your "print s" is in fact inside the loop, since the for loop is indented 
> with 4 spaces, and "print s" is indented with 1 tab = 8 spaces. It just 
> doesn't look like that to you.
> 
> It looks like you're coding in python 2. If you're new to python, I'd 
> recommend using a python 3 version, maybe 3.4 or 3.5. You can easily pick up 
> python 2 later if you need to maintain old code. Of course, it's not a big 
> deal learning python 3 if you know python 2 either, but why spend energy on 
> it?
> 
> Cheers
> Paul

Thanks.:) I use gedit in ubuntu 1
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-23 Thread shiva upreti
On Sunday, September 20, 2015 at 8:11:18 PM UTC+5:30, Laura Creighton wrote:
> The discussion about why or why not to use a bare except has gotten us
> away from the problem reported, which is "why is my script hanging?"
> 
> In a message of Sat, 19 Sep 2015 17:18:12 +0100, Mark Lawrence writes:
> >> I am learning python. I wrote a script using requests module.
> >> The scripts runs fine for sometime, but after a while it hangs. When I 
> >> press CTRL+C it shows ConnectionError even though I have included 
> >> exception handling.
> >> I am not sure as to why it cant handle ConnectionError when the script 
> >> runs for a long time.
> >>
> >> This is a part(causing issues) of the script I am running:
> >>
> >> while(k<46656):
> >>j=res[k]
> >>url="http://172.16.68.6:8090/login.xml"; 
> >>query_args = {'mode':'191', 'username':str(i), 
> >> 'password':str(j), 'a':'1442397582010', 'producttype':'0'}
> >>
> >>try:
> >>r=requests.post(url, data=query_args)
> >>except:
> >>print "Connection error"
> >>time.sleep(30)
> >>continue
> >>
> >>html=r.text
> >>if(len(html) < 10):
> >>continue
> >>
> >>if("The system could not log you on" not in html):
> >>print "hello"
> >>filehandle=open("ids", "a")
> >>filehandle.write(str(i)+'\n')
> >>filehandle.write(str(j)+'\n')
> >>filehandle.close()
> >>break
> >>
> >>k=k+1
> >>
> >> Any help will be highly appreciated.
> 
> So, when it hangs there are two main problems you can have.  One sort
> is that the other side, http://172.16.68.6:8090/ it in itself
> configured to only let people use a connection for a certain amount of
> time.  If you are using it for longer, it will disconnect you.  Or the
> other sort is that the other side disconnects people who have been
> silent for a certain amount of time.  If you haven't send anything for
> a certain amount of time it will log you off.  There are lots of other
> things that work this way -- the system may see many attempts to login
> and think you are trying to break into the system, the machine may
> have crashed ... but the bottom line is that the reason your script
> hangs is that there is nobody there on the other end.
> 
> The other sort of problem you can have is that the other end is
> alive and well and talking to you, but you don't understand what
> you are getting, and you are ignoring things you don't understand.
> This can look exactly the same.
> 
> To find out what is going on you need to log what it is that you
> are getting, to see if the answer is 'nothing' or 'garbage'.
> 
> Laura

Hi
If my script hangs because of the reasons you mentioned above, why doesnt it 
catch ConnectionError?
My script stops for a while and when I press CTRL+C, it shows ConnectionError 
without terminating the process, and the script resumes from where it left off.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
Thank you. I didnt know about keyboard interrupt exception.
It means my code hangs without raising any exceptions, what should i do in this 
case?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
Thank you Cameron.
I think the problem with my code is that it just hangs without raising any 
exceptions. And as mentioned by Laura above that when I press CTRL+C, it just 
catches that exception and prints ConnectionError which is definitely a lie in 
this case as you mentioned.
As my code doesnt raise any exception by itself, instead just hangs, I wont be 
able to characterize the exceptions and handle them individually.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
On Thursday, September 24, 2015 at 4:09:04 PM UTC+5:30, Laura Creighton wrote:
> In a message of Wed, 23 Sep 2015 19:49:17 -0700, shiva upreti writes:
> >Hi
> >If my script hangs because of the reasons you mentioned above, why doesnt it 
> >catch ConnectionError?
> >My script stops for a while and when I press CTRL+C, it shows 
> >ConnectionError without terminating the process, and the script resumes from 
> >where it left off.
> 
> This is exactly what you asked it to do. :)
> 
> >>try:
> >>r=requests.post(url, data=query_args)
> >>except:
> >>print "Connection error"
> >>time.sleep(30)
> >>continue
> 
> try to do something until you get an Exception.  Since that is a
> naked except, absolutely any Exception will do.  That you
> print out 'Connection error' doesn't mean that you are only
> catching exceptions raised by trying to send something to the
> other end ... any Exception will do.
> 
> So what happens when you press Control-C?
> 
> You get a KeyboardInterrupt exception! :)
> 
> see: https://docs.python.org/2/library/exceptions.html
> 
> And  you are catching it :)
> And when you catch it you print  Connection error and keep on
> trying.
> 
> This is why people were telling you that naked try:except: pairs,
> are rarely what you want.  You didn't want to catch control-c but
> you caught it anyway.
> 
> Laura

Thank you. I didnt know about keyboard interrupt exception.
It means my code hangs without raising any exceptions, what should i do in this 
case? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
On Thursday, September 24, 2015 at 4:09:04 PM UTC+5:30, Laura Creighton wrote:
> In a message of Wed, 23 Sep 2015 19:49:17 -0700, shiva upreti writes:
> >Hi
> >If my script hangs because of the reasons you mentioned above, why doesnt it 
> >catch ConnectionError?
> >My script stops for a while and when I press CTRL+C, it shows 
> >ConnectionError without terminating the process, and the script resumes from 
> >where it left off.
> 
> This is exactly what you asked it to do. :)
> 
> >>try:
> >>r=requests.post(url, data=query_args)
> >>except:
> >>print "Connection error"
> >>time.sleep(30)
> >>continue
> 
> try to do something until you get an Exception.  Since that is a
> naked except, absolutely any Exception will do.  That you
> print out 'Connection error' doesn't mean that you are only
> catching exceptions raised by trying to send something to the
> other end ... any Exception will do.
> 
> So what happens when you press Control-C?
> 
> You get a KeyboardInterrupt exception! :)
> 
> see: https://docs.python.org/2/library/exceptions.html
> 
> And  you are catching it :)
> And when you catch it you print  Connection error and keep on
> trying.
> 
> This is why people were telling you that naked try:except: pairs,
> are rarely what you want.  You didn't want to catch control-c but
> you caught it anyway.
> 
> Laura

Thank you. I didnt know about keyboard interrupt exception.
It means my code hangs without raising any exceptions, what should i do in this 
case? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ConnectionError handling problem

2015-09-24 Thread shiva upreti
On Friday, September 25, 2015 at 10:55:45 AM UTC+5:30, Cameron Simpson wrote:
> On 24Sep2015 20:57, shiva upreti  wrote:
> >Thank you Cameron.
> >I think the problem with my code is that it just hangs without raising any 
> >exceptions. And as mentioned by Laura above that when I press CTRL+C, it 
> >just catches that exception and prints ConnectionError which is definitely a 
> >lie in this case as you mentioned.
> 
> Update it to report the _actual_ exception received. (If any.) At least then 
> you will be sure.
> 
> >As my code doesnt raise any exception by itself, instead just hangs,
> 
> So, no "ConnectionError" message?
> 
> >I wont be able to characterize the exceptions and handle them individually.
> 
> Can you repost you code once it is modified to display the precise exception.
> 
> Note that one easy way to catch all but progressively handle specific 
> exceptions looks like this:
> 
>   try:
>  ... code ...
>   except OSError as e:
> print OSError received, specifics are:", e
>   except Exception as e:
> print "unhandled exception:", e
> break
> 
> and so on, inserting the exception types _above_ the final "except" as you 
> add 
> actions for them.
> 
> Cheers,
> Cameron Simpson 

Hi Cameron.
I think you may have misunderstood my problem.
When my code runs it doesnt throw any exception. It just hangs(stops executing) 
for unknown reasons. I want to know why. It doesnt even throw ConnectionError 
unless I press CTRL+C(only because I hard coded ConnectionError).
I can repost the whole problem again if you want me to.
Thanks.:)

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


Re: ConnectionError handling problem

2015-09-29 Thread shiva upreti
On Friday, September 25, 2015 at 12:55:01 PM UTC+5:30, Cameron Simpson wrote:
> On 24Sep2015 22:46, shiva upreti  wrote:
> >On Friday, September 25, 2015 at 10:55:45 AM UTC+5:30, Cameron Simpson wrote:
> >> On 24Sep2015 20:57, shiva upreti  wrote:
> >> >Thank you Cameron.
> >> >I think the problem with my code is that it just hangs without raising 
> >> >any 
> >> >exceptions. And as mentioned by Laura above that when I press CTRL+C, it 
> >> >just catches that exception and prints ConnectionError which is 
> >> >definitely 
> >> >a lie in this case as you mentioned.
> 
> Ok. You original code says:
> 
>   try:
> r=requests.post(url, data=query_args)
>   except:
> print "Connection error"
> 
> and presumably we think your code is hanging inside the requests.post call? 
> You 
> should probably try to verify that, because if it is elsewhere you need to 
> figure out where (lots of print statements is a first start on that).
> 
> I would open two terminals. Run your program until it hangs in one.
> 
> While it is hung, examine the network status. I'll presume you're on a UNIX 
> system of some kind, probably Linux? If not it may be harder (or just require 
> someone other than me).
> 
> If it is hung in the .post call, quite possibly it has an established 
> connecion 
> to the target server - maybe that server is hanging.
> 
> The shell command:
> 
>   netstat -rn | fgrep 172.16.68.6 | fgrep 8090
> 
> will show every connection to your server hosting the URL 
> "http://172.16.68.6:8090/login.xml";. That will tell you if you have a 
> connection (if you are the only person doing the connecting from your 
> machine).
> 
> If you have the "lsof" program (possibly in /usr/sbin, so "/usr/sbin/lsof") 
> you 
> can also examine the state of your hung Python program. This:
> 
>   lsof -p 12345
> 
> will report on the open files and network connections of the process with pid 
> 12345. Adjust to suit: you can find your program's pid ("process id") with 
> the 
> "ps" command, or by backgrounding your program an issuing the "jobs" command, 
> which should show the process id more directly.
> 
> Cheers,
> Cameron Simpson 

Hi Cameron.
Yes I use ubuntu 14.04. I will try what you suggested. But I cant understand 
one thing, for whatever reason the script is hanging, why does it resumes 
almost instantaneously when I press CTRL+C.
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list