Share Code Tips

Devyn Collier Johnson devyncjohnson at gmail.com
Fri Jul 19 15:51:23 CEST 2013


Aloha Python Users!

I have some coding tips and interesting functions that I want to share 
with all of you. I want to give other programmers ideas and inspiration. 
It is all Python3; most of it should work in Python2. I am a Unix/Linux 
person, so some of these will only work on Unix systems. Sorry Microsuck 
users :-D ;-)

All of the below Python3 code came from Neobot v0.8dev. I host an 
artificial intelligence program on Launchpad (LP Username: 
devyncjohnson-d). I have not released my Python version yet. The current 
version of Neobot (v0.7a) is written in BASH and Python3.

To emulate the Linux shell's date command, use this Python

function def DATE(): print(time.strftime("%a %B %d %H:%M:%S %Z %Y"))

Want an easy way to clear the terminal screen? Then try this:

def clr(): os.system(['clear','cls'][os.name == 'nt'])

Here are two Linux-only functions:

def GETRAM(): print(linecache.getline('/proc/meminfo', 
1).replace('MemTotal:', '').strip()) #Get Total RAM in kilobytes#
def KDE_VERSION(): print(subprocess.getoutput('kded4 --version | awk -F: 
\'NR == 2 {print $2}\'').strip()) ##Get KDE version##

Need a case-insensitive if-statement? Check this out:

if 'YOUR_STRING'.lower() in SOMEVAR.lower():

Have a Python XML browser and want to add awesome tags? This code would 
see if the code to be parsed contains chess tags. If so, then they are 
replaced with chess symbols. I know, many people hate trolls, but trolls 
are my best friends. Try this:

if '<chess_'.lower() in PTRNPRS.lower(): DATA = 
re.sub('<chess_white_king/>', '♔', PTRNPRS, flags=re.I); DATA = 
re.sub('<chess_white_queen/>', '♕', DATA, flags=re.I); DATA = 
re.sub('<chess_white_castle/>', '♖', DATA, flags=re.I); DATA = 
re.sub('<chess_white_bishop/>', '♗', DATA, flags=re.I); DATA = 
re.sub('<chess_white_knight/>', '♘', DATA, flags=re.I); DATA = 
re.sub('<chess_white_pawn/>', '♙', DATA, flags=re.I); DATA = 
re.sub('<chess_black_king/>', '♚', DATA, flags=re.I); DATA = 
re.sub('<chess_black_queen/>', '♛', DATA, flags=re.I); DATA = 
re.sub('<chess_black_castle/>', '♜', DATA, flags=re.I); DATA = 
re.sub('<chess_black_bishop/>', '♝', DATA, flags=re.I); DATA = 
re.sub('<chess_black_knight/>', '♞', DATA, flags=re.I); PTRNPRS = 
re.sub('<chess_black_pawn/>', '♟', DATA, flags=re.I)

For those of you making scripts to be run in a terminal, try this for a 
fancy terminal prompt:

INPUTTEMP = input('User ≻≻≻')


I may share more code later. Tell me what you think of my coding style 
and tips.


Mahalo,

Devyn Collier Johnson
DevynCJohnson at Gmail.com



More information about the Python-list mailing list