Some help in refining this regex for CSV files
Hi guys, I've to deal with CSVs that look like following CSV (with one header and 3 legit rows where each legit row has 3 columns) Some info Date: 12/6/2012 Author: Some guy Total records: 100 header1, header2, header3 one, two, three one, "Python is great, so are other languages, isn't ?", three one, two, 'some languages, are realyl beautiful\r\n, I really cannot deny \n this \t\t\t fact. \t\t\t\tthis fact alone is amazing' So inside this CSV, there will always be bad lines like the top 4 (they could end up in the beginning, in the middle and even in the last). So above sample, csv has 3 legit lines and a header. I want to read those three lines and here is a regex that I came up with (which clearly isn't working) #print line pattern = r"([^\t]+\t|,+)" matches = re.match(pattern, line) Do you've any better ideas guys? I will really appreciate all help. -- http://mail.python.org/mailman/listinfo/python-list
Cannot get past this string related issue
Greetings, I hope you're doing well. I'm stuck in a strange issue,
most likely due to my own ignorance. I'm reading a config file using
ConfigParser module and passing database related info to _mssql.
Following doesn't work
config = ConfigParser.ConfigParser()
config.read('configs.txt')
server_info = config.get("DB_INFO","server")
db = config.get("DB_INFO","database")
username = config.get("DB_INFO","user")
pwd = config.get("DB_INFO","password")
print server_info,db,username,pwd
conn =
_mssql.connect(server=server_info,database=db,user=username,password=pwd)
but following does work
conn =
_mssql.connect(server='server',database='database',user='user',password='password')
Config file looks like following
[DB_INFO]
server = "server"
database = "database"
user = "user"
password = "password"
But I cannot figure out why? Any ideas or help will be highly
appreciated. Thanks!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Cannot get past this string related issue
On Apr 26, 7:39 pm, Thomas Rachel wrote:
> Am 26.04.2011 15:48, schrieb Oltmans:
>
>
>
>
>
>
>
>
>
> > Following doesn't work
>
> > config = ConfigParser.ConfigParser()
> > config.read('configs.txt')
> > server_info = config.get("DB_INFO","server")
> > db = config.get("DB_INFO","database")
> > username = config.get("DB_INFO","user")
> > pwd = config.get("DB_INFO","password")
> > print server_info,db,username,pwd
> > conn =
> > _mssql.connect(server=server_info,database=db,user=username,password=pwd)
>
> > but following does work
>
> > conn =
> > _mssql.connect(server='server',database='database',user='user',password='pa
> > ssword')
>
> Ok, if you are this far: what prevents you from trying
>
> print server_info, db, username, pwd
>
> and being aware that IF there are " around, they are not part of the
> string representation, but they are really there.
>
> > Config file looks like following
>
> > [DB_INFO]
> > server = "server"
> > database = "database"
> > user = "user"
> > password = "password"
>
> I think if you will have seen the output above, you will probably see
> what is wrong here: too many "s. :-)
Many thanks, really appreciate help.
>
> HTH & HAND!
>
> Thomas
--
http://mail.python.org/mailman/listinfo/python-list
Unable to handle File Open dialog (using Pamie)
Hi all,
I'm new to Python and am automating few tasks using Pamie. Everything
worked well until I had to handle the File Open Dialog. I mean I'm
trying to automate the file upload process using Pamie. Basically I
just want to automate the process of file upload. I want to
automatically hit the Browse button and then enter 'C:\image1.jpg' in
the File Name text field and then hit the Open button (all using
Pamie, winguiauto or whatever would give me the solution :-)
Here is my html ( file is stored in my PC at C:\\Test\Test.html )
and here is my source
ie.navigate("C:\Test\Test.html")
ie.buttonClick('upload')
handle = winGuiAuto.findTopWindow(wantedText="Choose file")
print 'handle ='+ str(handle)
p=handlePopup('ChooseFile','&Open')
p.enterTextAndClickControl(handle,('C:\image1.jpg','&Open'))
p.run()
now when I run the above program the Browse button gets clicked and
File Open dialog pops up but 'c:\image1.jpg' (without quotes) is not
entered in the File Name field and neither the Open button gets
clicked. Also I get this error in the console
--
Traceback (most recent call last):
File "firsttest.py", line 26, in
p.enterTextAndClickControl(handle,('C:\image1.jpg','&Open'))
File "C:\Python25\lib\site-packages\cModalPopUp.py", line 113, in
enterTextAn
ClickControl
wantedClass="Edit")
File "C:\Python25\lib\site-packages\winGuiAuto.py", line 167, in
findControl
selectionFunction=selectionFunction)
File "C:\Python25\lib\site-packages\winGuiAuto.py", line 235, in
findControls
return searchChildWindows(topHwnd)
File "C:\Python25\lib\site-packages\winGuiAuto.py", line 213, in
searchChildW
ndows
childWindows)
TypeError: an integer is required
--
I've searched Internet, searched usenet, scratched my head but nothing
worked. Also, I tried joining the Pamie User group but I couldn't. So
I will really appreciate your help/insights/ideas/hints/anythiing that
can help me fix the problem.
Thanks,
Rolf
--
http://mail.python.org/mailman/listinfo/python-list
A SSH error during put operation
Hey all,
I've been using Paramiko for sometime now and I never had any
problems. I've already submitted this question to Paramiko mailling
list but I thought I should post it in CLP as someone might have used
it in past. I'm using Paramiko for SSH. Are there any other good SSH
libraries that you've found useful--please let me know?
There is this script that used to work absolutely fine. But for some
reason it's broken now. First, here is the script. Error is pasted at
the end. Please help as I've searched the Internet, archives but
couldn't find anything and it's been quite a few hours now. I will
really appreciate any help. Thanks in advance.
Script:
from __future__ import with_statement
import paramiko
import base64,os, sys
from paramiko import AutoAddPolicy, SSHClient
from decimal import *
class CustomException(Exception):
def __init__(self, value):
self.parameter = value
def __str__(self):
return repr(self.parameter)
def ConnectCopy(domainInfo, uname, pwd,
portNumber,zipName,completePath):
#domainInfo is a list, where domainInfo[0] = host name and
#domainInfo[1] is the remote path.
#
#zipName is the name of zip file. It will be appended with
domainInfo[1] so
#it will look like c:\Test\ABC.zip
#
#completePath is the local file path , that we intend to copy to
remote host
domainName=""
domainName=domainInfo[0].strip()
client= paramiko.SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
print 'Complete Path= '+completePath
try:
client.connect
(domainName,portNumber,username=uname,password=pwd)
except CustomException, (e):
print "Error="+e.parameter
print "Domain Info= "+domainInfo[1]
try:
sftp=client.open_sftp()
sftp.put(os.path.normpath(completePath),os.path.normpath
(domainInfo[1])+"\\"+zipName)
sys.stdout.write('\n')
print 'File has been copied'
except CustomException,(e):
print "Error = "+e.parameter
sys.exit()
sftp.close()
client.close()
if __name__=="__main__":
ConnectCopy(['example.example.com','C:\\test'],'username','pwd',
8922,'ABC.zip','C:\\ABC.zip')
and here is the Error:
Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.
C:\Release>connectdeploy1.py
Traceback (most recent call last):
File "C:\Release\ConnectDeploy1.py", line 56, in
ConnectCopy(['example.example.com','C:\\test'],'username','pwd',
8922,'ABC.zip','C:\\ABC.zip')
File "C:\Release\ConnectDeploy1.py", line 39, in ConnectCopy
sftp.put(os.path.normpath(completePath),os.path.normpath(domainInfo
[1]))
File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
539, in put
fr = self.file(remotepath, 'wb')
File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
238, in ope
n
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
589, in _re
quest
return self._read_response(num)
File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
637, in _re
ad_response
self._convert_status(msg)
File "C:\Python25\lib\site-packages\paramiko\sftp_client.py", line
667, in _co
nvert_status
raise IOError(text)
IOError: SfsStatusCode.Failure
--
http://mail.python.org/mailman/listinfo/python-list
Help needed to retrieve text from a text-file using RegEx
Here is the scenario:
It's a command line program. I ask user for a input string. Based on
that input string I retrieve text from a text file. My text file looks
like following
Text-file:
-
AbcManager=C:\source\code\Modules\Code-AbcManager\
AbcTest=C:\source\code\Modules\Code-AbcTest\
DecConnector=C:\source\code\Modules\Code-DecConnector\
GHIManager=C:\source\code\Modules\Code-GHIManager\
JKLConnector=C:\source\code\Modules\Code-JKLConnector
-
So now if I run the program and user enters
DecConnector
Then I'm supposed to show them this text "C:\source\code\Modules\Code-
DecConnector" from the text-file. Right now I'm retrieving using the
following code which seems quite ineffecient and inelegant at the same
time
with open('MyTextFile.txt') as file:
for line in file:
if mName in line: #mName is the string that
contains user input
Path =str(line).strip('\n')
tempStr=Path
Path=tempStr.replace(mName+'=',"",1)
I was wondering if using RegEx will make this look better. If so, can
you please suggest a Regular Expression for this? Any help is highly
appreciated. Thank you.
--
http://mail.python.org/mailman/listinfo/python-list
Searching Google?
Hey all, I want to search Google.com using a specific keyword and I just want to read back the response using Pyhon. After some thorough Googling I realized that I probably need a Search API key to do that. Is that correct? Now, I don't have a search key so is there a workaround? Please enlighten me. Thanks, Oltmans -- http://mail.python.org/mailman/listinfo/python-list
Printing digits in one place
I'm writing a file-transfer program and I'm receiving bytes transferred in a function. Now I would like to print bytes transfered in one place e.g. Bytes Transfered so far X and X will increase and cursor should stay at this position. I don't want to use any 3rd party module for this. Can I somehow do that without using any third-party module? I've been able to do this with Console module available at http://effbot.org/zone/console-handbook.htm but I would want to do this without the Console module. Actually , I'm able to initialize the Console module and print the bytes transferrred information but I can't find a way to exit from Console module so that my other functions can proceed with normal display using 'print' statement. Any ideas will be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
How to store passwords?
I'm writing a program in which I will ask users to enter user name and password once only. It's a console based program that will run on Windows XP. Actually, I'm trying to provide the similar functionality as "Remember me" thing in browsers. For that, I will need to store user name and passwords on the disk. I don't have a background in Crypto so how do you suggest I do that? What algorithms shall I be using? Moreover, I cannot use a whole library to do that due to certain issues. However, I can use like 1--2 files that will be shipped along with the main script. Any ideas? Any help will be really appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to store passwords?
On Jan 8, 1:55 am, "Sebastian Bassi" wrote: > In general you don't store the password, but a "hash" of it. Then when > the user logs-in, you hash it and compare the result with the stored > hash. > About hash, use sha, look > here:http://docs.python.org/library/hashlib.html#module-hashlib But the thing is that I will ask the user for user name and password only once i.e. when they start the application for the first time. After that, I'm not supposed to ask the user name and password again. So in this scenario, if I store a hash on the disk I cannot retrieve plain-text string back from my hash as I've to send user name and password to the server in plain-text. -- http://mail.python.org/mailman/listinfo/python-list
Indentifying types?
I'm reading from a file that contains text like 5 google_company apple_fruit pencil_object 4 test_one tst_two When I read the integer 5 I want to make sure it's an integer. Likewise, for strings, I want to make sure if something is indeed a string. So how do I check types in Python? I want to check following types 1- integers 2- strings 3- testing types of a particular class 4- decimal/floats Please excuse my ignorance & enlighten me. I will really appreciate any help. Thanks, Oltmans -- http://mail.python.org/mailman/listinfo/python-list
How to extract some text?
I'm at a loss to figure out how to extract some text from a string.
Here is a string:
setTimeout("location.href='http://youtube.example.com/login.aspx'",
5000);
and I want to only retrieve the URL from above i.e I only want this
http://youtube.example.com/login.aspx from the above string. Any ideas/
help is highly appreciated.
Thanks,
Oltmans
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to extract some text?
On Mar 9, 3:37 am, Chris Rebert wrote: > Learn about the methods of the string class > (str):http://docs.python.org/library/stdtypes.html#id4 > > You'll probably be most interested in .split() OK, thanks I got it. I was trying to use Regex but .split() just worked like a charm. Thank you ;) > > Cheers, > Chris > > -- > I have a blog:http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
calling class methods from class methods, help?
I've a multithreaded program in which I've to call class methods from class methods. Here is how my code look like (excluding imports),. Any help is highly appreciated. #!/usr/bin/env python class Requests(Thread): def __init__(self, times): Thread.__init__(self) self.times=times self.name='' def run(self): sites=['example.com','example1.com'] for i in range(0,self.times): for site in sites: self.name = site self.html=SendRequest() # This line throws an error def SendRequest(self): #A class method # it sends a request to website using mechanize library def startThis(times,reqs): threads=[] for i in range (0,reqs): owner=Requests(times) owner.start() threads.append(owner) for thread in threads: thread.join() if __name__=="__main__": #I want to create 2 threads, each of them will execute twice. At least that is the intention. startThis(2,2) -- http://mail.python.org/mailman/listinfo/python-list
Re: calling class methods from class methods, help?
On Mar 11, 10:08 pm, Oltmans wrote: > self.html=SendRequest() # This line throws an error and error says NameError: global name '_Requests_SendRequest' is not defined. -- http://mail.python.org/mailman/listinfo/python-list
Re: calling class methods from class methods, help?
On Mar 11, 11:00 pm, Piet van Oostrum wrote: > self.html=self.SendRequest() > -- Thank you, everyone, for the help. Appreciate that. > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: [email protected] Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
An error in threading.py?
Hi, all. I'm trying to use Mechanize in a multithreaded program--
purpose of which is to fill out a form on a website using concurrent
threads. Guys, trust me I've spent a lot of time to figure out the
problem but I'm completed puzzled. Firstly, I've listed the errors and
then the program listing (with imports omitted)
Error:
Traceback (most recent call last):
File "C:\Python25\lib\threading.py", line 460, in __bootstrap
self.run()
File "tmechanize.py", line 21, in run
with lock:
NameError: global name 'lock' is not defined
Program:
-
#!/usr/bin/env python
requestNumber=0
class Requests(Thread):
def __init__(self, times):
Thread.__init__(self)
self.times=times
self.html=' '
self.requestTime={}
self.starttime=0
self.endtime=0
self.br= Browser()
def run(self):
for i in range(0,self.times):
self.starttime=time.clock()
self.SendRequest()
self.endtime=time.clock()
with lock:
global requestNumber
requestNumber += 1
print 'locking the time'
self.requestTime[requestNumber]=self.endtime -
self.starttime
def SendRequest(self): #A class method
# it sends a request to website using mechanize library
self.br.add_password("https://example.com/admin";, "admin",
"admin")
res=self.br.open("https://example.com/admin";)
print 'Successfully loggedin '
self.html=res.read()
print 'Filling in the form'
self.br.select_form(name="formOne")
self.br["textbox"]="www.google.com"
self.br["textBox1"]='www.example.com'
self.br["users[0].firstName"]="firstName"
self.br["users[0].lastName"]="LastName"
self.br["users[0].emailAddress"]="[email protected]"
print 'Submitting the form'
resp=self.br.submit()
self.html=resp.read()
def startThis(times,reqs):
#print 'Threads ='+str(times)
#print 'Reques/Thread ='+ str(maxReqs)
threads=[]
for i in range (0,reqs):
owner=Requests(times)
owner.start()
threads.append(owner)
for thread in threads:
thread.join()
if __name__=="__main__":
#I want to create 2 threads, each of them will execute twice. At
least that is the intention.
startThis(2,2)
--
http://mail.python.org/mailman/listinfo/python-list
Searching and replacing text ?
Hi,
I'm new to Python (and admittedly not a very good programmer) and I've
come across a scenario where I've to search and replace text in a
file.
For the sake of an example, I'm searching for every occurence of the
text
[[http://www.hotmail.com -> Hotmail]]
I've to replace it with
[http://www.hotmail.com Hotmail]
I've come up with following scheme
p=re.compile(r'\[\[')
q=re.compile(r'->')
p.sub('[',txt)
q.sub('\b',txt)
Give that I don't have very strong RegEX background, this doesn't look
very elegant. Is there some other way I can accomplish the same thing?
Moreover, please note that I'm using 'p' and 'q' for two regex and
then calling 'sub()' on both p and q. Can't I just do that by
employing one RegEx and then calling sub() only once?
Please enlighten me. Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list
Regex help needed!
Hello,. everyone.
I've a string that looks something like
lksjdfls kdjff lsdfs sdjfls sdfsdwelcome
>From above string I need the digits within the ID attribute. For
example, required output from above string is
- 35343433
- 345343
- 8898
I've written this regex that's kind of working
re.findall("\w+\s*\W+amazon_(\d+)",str)
but I was just wondering that there might be a better RegEx to do that
same thing. Can you kindly suggest a better/improved Regex. Thank you
in advance.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Regex help needed!
On Dec 21, 5:05 pm, Umakanth wrote:
> How about re.findall(r'\d+(?:\.\d+)?',str)
>
> extracts only numbers from any string
>
Thank you. However, I only need the digits within the ID attribute of
the DIV. Regex that you suggested fails on the following string
lksjdfls kdjff lsdfs sdjfls sdfsdwelcome
hello, my age is 86 years old and I was born in 1945. Do you know that
PI is roughly 3.1443534534534534534
> ~uk
>
> On Dec 21, 4:38 pm, Oltmans wrote:
>
> > Hello,. everyone.
>
> > I've a string that looks something like
> >
> > lksjdfls kdjff lsdfs sdjfls > = "amazon_35343433">sdfsdwelcome
> >
>
> > From above string I need the digits within the ID attribute. For
> > example, required output from above string is
> > - 35343433
> > - 345343
> > - 8898
>
> > I've written this regex that's kind of working
> > re.findall("\w+\s*\W+amazon_(\d+)",str)
>
> > but I was just wondering that there might be a better RegEx to do that
> > same thing. Can you kindly suggest a better/improved Regex. Thank you
> > in advance.
>
>
--
http://mail.python.org/mailman/listinfo/python-list
unittest help needed!
Hi Python gurus,
I'm quite new to Python and have a problem. Following code resides in
a file named test.py
---
import unittest
class result(unittest.TestResult):
pass
class tee(unittest.TestCase):
def test_first(self):
print 'first test'
print '-'
def test_second(self):
print 'second test'
print '-'
def test_final(self):
print 'final method'
print '-'
r = result()
suite = unittest.defaultTestLoader.loadTestsFromName('test.tee')
suite.run(r)
---
Following is the output when I run it
---
final method
-
first test
-
second test
-
final method
-
first test
-
second test
-
---
Looks like it's running every test twice, I cannot figure out why?
Shouldn't output be more like
---
final method
-
first test
-
second test
-
---
Please help me solve the problem. Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list
Re: unittest help needed!
On Jan 14, 11:46 pm, [email protected] wrote: > When you run test.py, it gets to the loadTestsFromName line. There, it > imports the module named "test" in order to load tests from it. To > import > that module, it runs test.py again. By the time it finishes running the > contents of test.py there, it has run all of your tests once, since part > of test.py is "suite.run(r)". Having finished that, the import of the > "test" Many thanks, really appreciate your insight. Very helpful. I need a program design advice. I just want to know what's the gurus way of doing it? I've a unittest.TestCase derived class that have around 50 test methods. Design is almost similar to following --- import unittest class result(unittest.TestResult): pass class tee(unittest.TestCase): def test_first(self): print 'first test' process(123) def test_second(self): print 'second test' process(564) def test_third(self): print 'final method' process(127863) if __name__=="__main__": r = result() suite = unittest.defaultTestLoader.loadTestsFromName('test.tee') suite.run(r) --- As you can see, every test method is almost same. Only difference is that every test method is calling process() with a different value. Also, I've around 50 test methods coded that way. I just want to know: is there a way I can make things smaller/smarter/pythonic given the current design? If you think any information is missing please let me know. I will really really appreciate any insights. Many thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Want to call a method only once for unittest.TestCase--but not sure how?
Hello fellow python hackers, I'm not an expert when it comes to Python and I'm totally stuck in a situation. All of our unit tests are written using built-in 'unittest' module. We've a requirement where we want to run a method only once for our unit tests. Some background: all of our tests are sub-classes of unittest.TestCase module just like following (copy pasting from idle) class Calculator(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_add(self): print 'adder' print '---' def test_multiply(self): print 'multiplier' print '---' def test_divide(self): print '===' print 'Divide test' print '===' Our requirement is that for every unit test class we want to run a method only once. Method setUp() won't help because it will be called before every test method. I've tried using the following def __init__(self): unittest.TestCase.__init__(self) but it throws the following error E:\PyPy\Practice>python runner.py Traceback (most recent call last): suite = unittest.defaultTestLoader.loadTestsFromNames (['Tests.Calculator.Te stCase']) File "C:\Python25\lib\unittest.py", line 565, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "C:\Python25\lib\unittest.py", line 547, in loadTestsFromName return self.loadTestsFromTestCase(obj) File "C:\Python25\lib\unittest.py", line 507, in loadTestsFromTestCase return self.suiteClass(map(testCaseClass, testCaseNames)) TypeError: __init__() takes exactly 1 argument (2 given) So I'm completely stumped as to how to create a method that will only be called only once for Calculator class. Can you please suggest any ideas? Any help will be highly appreciated. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Help resolve a syntax error on 'as' keyword (python 2.5)
Hi, all. All I'm trying to do is to print the error message using the following code (copying/pasting from IDLE). def div(a,b): print a/b try: div(5,0) except Exception as msg: print msg but IDLE says (while highlighting the 'as' keyword) except Exception as msg: SyntaxError: invalid syntax I've searched the internet and I'm not sure what can cause this. Any help is highly appreciated. I'm using Python 2.5 on Windows XP. -- http://mail.python.org/mailman/listinfo/python-list
Adding methods from one class to another, dynamically
Hello Python gurus,
I'm quite new when it comes to Python so I will appreciate any help.
Here is what I'm trying to do. I've two classes like below
import new
import unittest
class test(unittest.TestCase):
def test_first(self):
print 'first test'
def test_second(self):
print 'second test'
def test_third(self):
print 'third test'
class tee(unittest.TestCase):
pass
and I want to attach all test methods of 'test'(i.e. test_first(),
test_second() and test_third()) class to 'tee' class. So I'm trying to
do something like
if __name__=="__main__":
for name,func in inspect.getmembers(test,inspect.ismethod):
if name.find('test_')!= -1:
tee.name = new.instancemethod(func,None,tee)
after doing above when I run this statement
print dirs(tee)
I don't see test_first(), test_second() and test_third() attached to
class 'tee'. Any ideas, on how can I attach methods of class 'test' to
class 'tee' dynamically? Any help is highly appreciated.
Many thanks and I look forward to any help.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Adding methods from one class to another, dynamically
Thank you for your help, Chris. Looks like I can now attach methods to
class 'tee'. However, after attaching methods to 'tee' when I try to
run them using suite.run() I don't see any of the methods running, I'm
sorry but I've no clue what's failing this. Any insights will be
highly appreciated. Here is the sample code
filename: check.py
---
import inspect
import unittest
class result(unittest.TestResult):
def addSuccess(self,test):
print str(test) + ' succeeded'
def addError(self,test,err):
print 'An error occured while running the test ' + str(test) +
' and error is = ' + str(err)
def addFailure(self,test,err):
print str(test) + " failed with an error =" + str(err)
class test(unittest.TestCase):
def test_first(self):
print 'first test'
def test_second(self):
print 'second test'
def test_third(self):
print 'third test'
import new
class tee(unittest.TestCase):
pass
if __name__=="__main__":
r = result()
for name,func in inspect.getmembers(test,inspect.ismethod):
if name.find('test_')!= -1:
setattr(tee, name, new.instancemethod(func,None,tee))
suite = unittest.defaultTestLoader.loadTestsFromName('check.tee')
suite.run(r)
---
Then line suite.run(r) should have run the methods that we just
attached, but it's not. I must be missing something here. Please
enlighten me.
Thanks.
On Feb 2, 1:25 am, Chris Rebert wrote:
> On Mon, Feb 1, 2010 at 12:06 PM, Oltmans wrote:
> > Hello Python gurus,
>
> > I'm quite new when it comes to Python so I will appreciate any help.
> > Here is what I'm trying to do. I've two classes like below
>
> > import new
> > import unittest
>
> > class test(unittest.TestCase):
> > def test_first(self):
> > print 'first test'
> > def test_second(self):
> > print 'second test'
> > def test_third(self):
> > print 'third test'
>
> > class tee(unittest.TestCase):
> > pass
>
> > and I want to attach all test methods of 'test'(i.e. test_first(),
> > test_second() and test_third()) class to 'tee' class. So I'm trying to
> > do something like
>
> > if __name__=="__main__":
> > for name,func in inspect.getmembers(test,inspect.ismethod):
> > if name.find('test_')!= -1:
> > tee.name = new.instancemethod(func,None,tee)
>
> This ends up repeatedly assigning to the attribute "name" of tee; if
> you check dir(tee), you'll see the string "name" as an entry. It does
> *not* assign to the attribute named by the string in the variable
> `name`.
> You want setattr():http://docs.python.org/library/functions.html#setattr
> Assuming the rest of your code chunk is correct:
>
> setattr(tee, name, new.instancemethod(func,None,tee))
>
> Cheers,
> Chris
> --http://blog.rebertia.com- Hide quoted text -
>
> - Show quoted text -
--
http://mail.python.org/mailman/listinfo/python-list
Re: Adding methods from one class to another, dynamically
On Feb 2, 2:14 am, Steve Holden wrote: > > Should not tee be subclassing test, not unittest.TestCase? > Thank you, Steve. This worked, but I've not clue why? Can you please enlighten me why sub-classing 'test' made it happen? Please. Thanks again. > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ > Holden Web LLC http://www.holdenweb.com/ > UPCOMING EVENTS: http://holdenweb.eventbrite.com/- Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Converting HTML to PDF using Python?
Hi Python superstars, Guys, any ideas on how to convert HTML files to PDF files? Or as an alternative, how to convert HTML files to an image file(jpeg/png/etc)? Ideally, the converted PDF/Image file should like exactly like the way HTML file looks in the browser. I really have no idea about this so I will really appreciate all the help. Thanks in advance and kindly pardon my ignorance. Thanks, Oltmans -- http://mail.python.org/mailman/listinfo/python-list
Hosting a Python based TCP server
Hi all, I'm writing a very small TCP server(written in Python) and now I want to host it on some ISP so that it can be accessed anywhere from the Internet. I've never done that before so I thought I should ask for some advice. Do you guys know any good ISP that can let me do that? Most importantly, what is usually involved in order to make this happen? Please pardon my ignorance and I will really appreciate your reply. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Line breaks in list causing a small formatting problem while joining the list
Hi Python gurus, hope you're doing well. I've a small problem. When I run the following code ___ >>> names = ['oltmans','abramhovic','\n','sal','lee'] >>> print '| ' + ' | '.join(names) | oltmans | abramhovic | | sal | lee _______ I get the output like above. However, I want it to output like below | oltmans | abramhovic | | sal | lee That is, there shouldn't be a space in the beginning of second line. The list can of course contain more than 5 elements. Any ideas? I will appreciate any hint. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Can someone please make it more pythonic or better?
Greetings Python superstars,
I've a directory structure like following
tests /
__init__.py
testfile.py
testfile.py contains following code
import unittest
class Calculator(unittest.TestCase):
def test_add(self):
print 'just add'
def test_divide(self):
print 'diviide'
def test_multiply(self):
print 'mul'
class Car(unittest.TestCase):
def test_start(self):
print 'start'
def test_move_right(self):
print 'move right'
def test_move_left(self):
print 'move left'
def test_stop(self):
print 'stop'
Now give the following user-input I want to get all test-names.
user-input = tests.testfile (get all test-names from all
unittest.TestCase derived classes in test.testfile)
user-input = tests.testfile.Car (get all test-names from the Car
class)
user-input = tests.testfile.Cacr.test_stop
and I'm doing it this the following way and I really think there has
to be more readable, more pythonic and more possibly short way to do
it
import unittest
import sys
import inspect
def get_test_names(full_name,module):
name = full_name.split('.')
loader = unittest.TestLoader()
if len(name) == 4:
return full_name
elif len(name) == 3:
exec "from %s.%s import %s" %(module,name[1],name[2])
return loader.getTestCaseNames(eval(name[2]))
elif len(name) == 2:
exec 'from %s import %s' % (module,name[1])
tests = []
for _name, obj in inspect.getmembers(sys.modules[full_name]):
if inspect.isclass(obj) and
issubclass(obj,unittest.TestCase):
exec "from %s.%s import %s" %
(module,name[1],obj.__name__)
tests.append(loader.getTestCaseNames(obj))
return tests
if __name__ == "__main__":
input = "tests.testfile"
module = input.split('.')[0]
_tests = get_test_names(input,module)
print _tests
So guys, can you kindly point me to a more Pythonic, more readable and
possible more short way to acheive this? I will really appreciate any
help. Many thanks in advance.
Best regards,
Oltmans
--
http://mail.python.org/mailman/listinfo/python-list
Kindly show me a better way to do it
Hi, I've a list that looks like following a = [ [1,2,3,4], [5,6,7,8] ] Currently, I'm iterating through it like for i in [k for k in a]: for a in i: print a but I was wondering if there is a shorter, more elegant way to do it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Kindly show me a better way to do it
On May 9, 1:53 am, superpollo wrote: > add = lambda a,b: a+b > for i in reduce(add,a): > print i This is very neat. Thank you. Sounds like magic to me. Can you please explain how does that work? Many thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Some help needed with small multi-threaded program!
I've a small multi-threaded program that is written by keeping
Producer-Consumer pattern in mind. In the Producer part of the program
we create new users by doing a POST to a certain web URL whereas in
the Consumer part of the program we try to login newly created users.
Problem is that program sort of runs fine, however, it never
terminates itself and, more importantly, it doesn't print last-three
lines of the program(which is important for my purposes). I've looked
at the docs, but I couldn't figure out a solution so if someone can
spot the problem and suggest a solution that will be highly
appreciated. Many thanks in advance.
-
#!/usr/bin/env python
import Queue
import re
import random
import time
import threading
import urllib2
import simplejson
from urllib2 import HTTPError
import urllib
base_url = "http://example.com/";
queue = Queue.Queue()
total_users = 0
#keeps the record of time it takes to create a user
create_user_times = {}
#keeps the record of time it takes to authenticate a user
login_user_times = {}
lock = threading.Lock()
errors = []
class User():
def
__init__(self,firstName,lastName,email,password,userName,active):
self.firstName = firstName
self.lastName = lastName
self.password = password
self.email = email
self.userName = userName
#producer
class CreateUsers(threading.Thread):
def __init__(self,queue,limit):
threading.Thread.__init__(self)
self.queue = queue
self.limit = limit
def create_user(self):
url = base_url + "users/"
email = "stokeywonder+"+str(random.randrange(0,10))
+"@example.com"
obj = {'firstName' : 'Coyotee',
'lastName' : 'Stevey', 'email' : email,
'password':'7887',
'userName':email
}
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE
5.5; Windows NT)')
req.add_header("Content-Type","application/json")
req.add_data(simplejson.dumps(obj))
try:
t = time.time()
f = urllib2.urlopen(req)
page = f.read()
if str(f.code) != '200':
pass
else:
create_user_times[obj['userName']] = str("%.
2f"%float(time.time() - t))
user = User(**obj)
self.queue.put(user)
except:
errors.append(obj['userName'])
def run(self):
global total_users
global lock
while total_users < self.limit:
lock.acquire()
try:
total_users += 1
finally:
lock.release()
self.create_user()
if total_users == self.limit:
try:
self.queue.task_done()
except ValueError:
pass
#Consumer
class TestService(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue = queue
def login(self,user):
user_name = user.userName
pwd = user.password
url = base_url+'u?uName='+user_name+'&pwd='+pwd
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
req = urllib2.Request(url)
req.add_header('User-Agent', user_agent)
try:
t = time.time()
f = urllib2.urlopen(req)
if str(f.code) != '200':
pass
else:
login_user_times[user_name] = str("%.
2f"%float(time.time() - t))
except:
errors.append(user_name)
def run (self):
while True:
user = self.queue.get()
if user:
self.login(user)
if __name__ == "__main__":
#limit = number of users
limit = 5
th = []
for i in range(2):
t = CreateUsers(queue,limit)
t1 = TestService(queue)
t.start()
t1.start()
th.append(t1)
th.append(t)
for t in th:
t.join()
print create_user_times
print '---'
print login_user_times
--
http://mail.python.org/mailman/listinfo/python-list
Does pickled objects work fine between different OS?
If I dump a Python dictionary into a file named "data.pkl" using Pickle module on a Linux operating system, will the data contained in "data.pkl" load fine in a Windows OS? I mean will I be able to load the dictionary data contained in "data.pkl" just fine on Windows XP? I could have tested it but don't have immediate access to a *nix based system so please enlighten me. All help will be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
How to improve this code?
Hello, Is there someway I can improve the following code(pythonically)? (Copying from IDLE) match=[1,2,3,4,5] def elementsPresent(aList): result=False if not aList: return False for e in aList: if e in match: result=True else: result = False return result elementsPresent([6,7,8,9,5]) # should return True because 5 is present in list named match. Is there somehow I can improve code in elementsPresent()? I'm not a very good programmer but I sense that idea of using a variable named 'result' inside elementsPresent() doesn't sound very good. Any ideas will be highly appreciated. Thanks, Oltmans -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
On Sep 15, 1:13 pm, Hendrik van Rooyen wrote: > > (i) a True if All the elements in match are in aList, else False? > (ii) a True if any one or more of the members of match are in aList? > (iii) Something else? That's a good question because I failed miserably in explaining my problem clearly. My original question isn't what I'm trying to solve. My apologies. I will try to explain here clearly. I'm using a 3rd- party library named Selenium (used for web-automation) and it has a method named is_element_present(ele) i.e. takes one element and return true if it finds this element in the page's HTML and returns false otherwise. Given this, I'm just trying to write a method are_elements_present(aList) whose job is to return True if and only if all elements in aList are present in page's HTML. So here is how are_elements_present() looks like def are_elements_present(eleLocators): elePresent=False if not eleLocators: return False for ele in eleLocators: if selenium.is_element_present(ele): elePresent=True else: elePresent=False print 'cannot find this element= '+str(ele) break return elePresent Now suppose page HTML contains with these IDs ( ID is an attribute like ) = div1,div2,div3,div4,div5,inp1,inp2 and if I call the above method this way are_elements_present ([div1,div2,inp1,inp2]) then it should return True. If I call like are_elements_present([div1,div2,div10,inp1]) it should return False. So I hope I've explained myself. Now all I'm looking for is to write are_elements_presents() in a more Pythonic way. So please let me know if I can write are_elements_present() in more smart/shorter way. Thanks a lot for your help, in advance. Best regards, Oltmans -- http://mail.python.org/mailman/listinfo/python-list
