Python recipes: Difference between revisions
From Wildsong
Jump to navigationJump to search
Brian Wilson (talk | contribs) mNo edit summary |
Brian Wilson (talk | contribs) mNo edit summary |
||
Line 1: | Line 1: | ||
== Tips and tricks == | |||
=== Simple file reader === | |||
# | with open(filename) as fp: | ||
for line in fp.readlines(): | |||
line = line.rstrip("\r\n") # remove trailing newline | |||
line = line.lstrip(" \t") # remove leading whitespace | |||
if not len(line): continue # skip blank lines | |||
# do stuff here | |||
=== Writing a log === | |||
=== Date stamps === | |||
import time | |||
=== Running commands === | |||
import subprocess | |||
try: | |||
retcode = subprocess.call("mycmd" + " myarg", shell=True) | |||
if retcode < 0: | |||
print >>sys.stderr, "Child was terminated by signal", -retcode | |||
else: | |||
print >>sys.stderr, "Child returned", retcode | |||
except OSError, e: | |||
print >>sys.stderr, "Execution failed:", e |
Revision as of 19:44, 2 December 2015
Tips and tricks
Simple file reader
with open(filename) as fp: for line in fp.readlines(): line = line.rstrip("\r\n") # remove trailing newline line = line.lstrip(" \t") # remove leading whitespace if not len(line): continue # skip blank lines # do stuff here
Writing a log
Date stamps
import time
Running commands
import subprocess try: retcode = subprocess.call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e