Last Tested in Python Version: 3.1.2
This is a class that I use in most of my scripts. It has handy functions. It has yet to be fully documented, I will hopefully take care of that when I have time.
Please feel free to post functions you'd like to add here, I'll gladly add them to the class.
Changelog:Code:#!/usr/bin/env python ##################### #Author: Riddle #Website: www.logicalgamers.com #E-mail: NONE #Version: 0.8.2 ##################### #Collection of useful and general functions import hashlib import sys import re import os import time import random class General: def __init__(self): pass def GetBetween(self, content, start, end): """Returns '' on no match""" r = content.split(start) if len(r) > 1: r = r[1].split(end) return r[0] return '' def md5Digest(self, Str1): a = hashlib.md5() #Create new MD5 object a.update(Str1.encode('utf-8')) #Prepares password string to be digested return a.hexdigest() #Returns the final outcome def Log_Error(self, Data, File_Name = 'Error Log.txt', Mode = 'a'): Target = open(os.getcwd()+self.sep()+File_Name, Mode) Target.write(Data) Target.close() def Paused_Exit(self): a = input("\nPress Enter To Exit...") sys.exit(1) def Str_To_File(self, str1, path, mode = "a"): f = open(path, mode) f.write(str1) f.close() def List_To_File(self, lst1, path, mode = "a", line_break = False): #Line Break adds a \n after each line f = open(path,mode) if line_break == False: f.writelines(lst1) else: for line in lst1: f.write(line+"\n") f.close() def File_To_List(self, path): f = open(path, "r") lines = f.readlines() new_list = [] for line in lines: new_list.append(line.strip()) f.close() return new_list def File_To_Str(self, path): f = open(path, "r") str1 = f.read() f.close() return str1 def De_Dupe_List(self, lst, case_sensitive = False): if case_sensitive == False: for item in lst: for citem in lst: if item != citem: if item.lower() == citem.lower(): lst.remove(citem) for item in lst: lst.remove(item) if not item in lst: lst.append(item) return lst def Find_All(self, pattern, strToSearch): #Find all matching strings with a Reg Ex. pattern = re.compile(pattern) return re.findall(pattern, strToSearch) def Dir_Exists(self,path): "Returns True if it exists" return os.path.isdir(path) def File_Exists(self,path): "Returns True if the file exists" return os.path.isfile(path) def Cur_Dir(self): "Returns Current Directory" return os.getcwd() def mkdir(self,path): "Makes Directory on Path" os.mkdir(path) def sep(self): return os.path.sep def strip_ml_tags(self, in_text): """Description: Removes all HTML/XML-like tags from the input text. Inputs: s --> string of text Outputs: text string without the tags >>> test_text = "Keep this Text <remove><me /> KEEP </remove> 123" >>> strip_ml_tags(test_text) 'Keep this Text KEEP 123' """ # Routine by Micah D. Cochran # Submitted on 26 Aug 2005 # This routine is allowed to be put under any license Open Source (GPL, BSD, LGPL, etc.) License # or any Propriety License. Effectively this routine is in public domain. Please attribute where appropriate. # convert in_text to a mutable object (e.g. list) s_list = list(in_text) i,j=0,0 while i < len(s_list): # iterate until a left-angle bracket is found if s_list[i] == '<': while s_list[i] != '>': # pop everything from the the left-angle bracket until the right-angle bracket s_list.pop(i) # pops the right-angle bracket, too s_list.pop(i) else: i=i+1 # convert the list back into text join_char='' return join_char.join(s_list) def GetInputValue(self, contentStr, nameStr, typeStr = "hidden"): """ GetInputValue(contentStr, nameStr, typeStr = "hidden") Gets the value of an input (from HTML4 Forms). -> contentStr: The HTML source to search for the input in. -> typeStr: By default it looks for hidden inputs. -> nameStr: Name of the input. Returns: -> String: Value when found -> None: None when fails. Raises Exception. -> Bool: False when any of the given arguments is not a string """ if contentStr.__class__ == str and typeStr.__class__ == str and nameStr.__class__ == str: try: return self.GetBetween(contentStr, "<input type="+typeStr+" name='"+nameStr+ "' value='", "'>") except: pass try: return self.GetBetween(contentStr, "<input type="+typeStr+" name=\""+nameStr+ "\" value=\"", "\">") except: pass try: return self.GetBetween(contentStr, "<input type='"+typeStr+"' name=\""+nameStr+ "\" value=\"", "\">") except: pass try: return self.GetBetween(contentStr, "<input type=\""+typeStr+"\" name=\""+nameStr+ "\" value=\"", "\">") except: pass try: return self.GetBetween(contentStr, "<input type='"+typeStr+"' name='"+nameStr+ "' value='", "'>") except: pass try: return self.GetBetween(contentStr, "<input type=\""+typeStr+"\" name='"+nameStr+ "' value='", "'>") except: #EXCEPTION HANDLING HERE!! return None return False def Sleep(self, secs): time.sleep(secs) return def RandFloat(self,low, high): return random.uniform(low,high)
- 6/30/2010: Added GetInputValue() function. Added version doc. in the classes.
- 7/4/2010: Version 0.8.2; Revamped GetInputValue(). Added Sleep(secs) and RandFloat(low,high).
Results 1 to 31 of 31
Thread: [Python] General Class
- 30 Jun. 2010 12:35am #1
[Python] General Class
Last edited by Riddle; 04 Jul. 2010 at 10:49pm.
- 01 Jul. 2010 01:51am #2
- 04 Jul. 2010 11:04pm #3
- 12 Sep. 2010 03:01am #4
Wouldn't it have been far more efficient to use regular expressions in your GetInputValue method? Seems like a lot of unnecessary code and guess work on your part :p
- 12 Sep. 2010 12:00pm #5
No one on LG seems to understand that regex is very useful and processor happy. As in it doesnt take up as much cpu/ram as something you made yourself. Thought it still wont take much up most likely.
No one liked that i used regex in one of my programs. They were like why dont you just use getbetween 50 times? >o
- 12 Sep. 2010 04:05pm #6
- 12 Sep. 2010 08:05pm #7
- 18 Sep. 2010 07:27pm #8
Yes, and no.
That was just something I had lying around from ancient times, so I just copied pasted. It worked for w/e I was using it for.
- 12 Jun. 2011 06:02pm #9
- 13 Jun. 2011 02:02pm #10
- 13 Jun. 2011 08:31pm #11
- 13 Jun. 2011 11:28pm #12
Should just use regular expressions.
- 14 Jun. 2011 12:55am #13
- 14 Jun. 2011 06:50am #14
- 14 Jun. 2011 04:48pm #15
- 14 Jun. 2011 11:11pm #16
Print out whatever results from the function call. Post what you get.
- 15 Jun. 2011 02:28am #17
I fixed it. I wasn't calling the master thing so it wasn't executing any of the coding. It does return as ['value to grab']. Anyway to remove the brackets and single quotes or do I just have to use the replace method or do I just slap it into an array?
EDIT: Just slapped it into an array and it worked perfectly fine, thanks guys.
- 15 Jun. 2011 02:32am #18
It should return as a list.
Code:print results[0]
- 15 Jun. 2011 02:38am #19
- 15 Jun. 2011 11:26am #20
- 16 Jun. 2011 02:37am #21
If you check out the function, it returns a list. In python terms, a list is basically an array. Every instance that matches your pattern will be in an array. You guys should read about lists and how to use them DiveIntoPython has a good basis of lists and how to use them.
- 16 Jun. 2011 03:09am #22
- 16 Jun. 2011 03:30am #23
Lists in Pythons are like arrays on steroids. You can do everything you can with regular arrays in other programming languages, plus so much more!
- 16 Jun. 2011 06:23am #24
^ Deserves to be in a signature quote.
On topic; I've been having a problem making a towns collector in python grabbing all the trash in the gsi page. It's displayed as so
Code:0:t0192995, 1:t010958, 2:039580
.................................................. ..................... ^ Minus the space.
- 16 Jun. 2011 06:45am #25
Your pattern is too general. You probably want to try and make it a little more specific. For instance, just tested and it grabbed them all:
Code:import re search = "0:t0192995, 1:t010958, 2:039580" matches = re.findall( "\d+\:([a-z]{0,1}\d+)", search) for eachMatch in matches: print "Match: " + eachMatch
Last edited by Artificial; 16 Jun. 2011 at 08:40am.
- 16 Jun. 2011 07:20am #26
- 16 Jun. 2011 10:11pm #27
- 17 Jun. 2011 02:23am #28
- 17 Jun. 2011 10:15am #29
- 17 Jun. 2011 09:12pm #30
You can use py2exe if you really need to compile. You can also use the .pyc files that are compiled when you run your scripts, however, they can be de-compiled (if it's an old source, not sure about 2.4+). I don't like parts a bits of the syntax, but as a whole, it isn't too bad.
See this: Why doesn't Python have a switch statement? - Stack Overflow
There are a few reasons provided why Python doesn't use switch statements. In my opinion, they're not needed at all. You can use work arounds if you really want to use switch statements:
Readable switch construction without lambdas or dictionaries Python recipes ActiveState Code
Exception-based Switch-Case Python recipes ActiveState Code
Using a Dictionary in place of a 'switch' statement Python recipes ActiveState Code
Then again, I suggest you just use if statements.
- 17 Jun. 2011 09:16pm #31