Python recipes: Difference between revisions

From Wildsong
Jump to navigationJump to search
Brian Wilson (talk | contribs)
Brian Wilson (talk | contribs)
Line 40: Line 40:
   except OSError, e:
   except OSError, e:
     print >>sys.stderr, "Execution failed:", e
     print >>sys.stderr, "Execution failed:", e
Run a command and fetch its output
  output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].splitlines()


=== Read the contents of a spreadsheet (ODS) ===
=== Read the contents of a spreadsheet (ODS) ===


PyUno is part of Apache OpenOffice.
PyUno is part of Apache OpenOffice.

Revision as of 04:46, 8 July 2016

Here are code snippets I can't seem to keep in my head between uses.

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

Redirect stdout

import sys
save_stdout = sys.stdout
sys.stdout = open('file', 'w')
print 'test'
sys.stdout = save_stdout

Writing a log

Date stamps

from datetime import datetime

datetime.now() # returns an object
datetime.datetime(2015, 12, 2, 12, 0, 28, 8580)

datetime.now().strftime("%Y-%m-%d %H:%M") # returns a formatted string like '2015-12-02 12:01'

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


Run a command and fetch its output

  output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].splitlines()

Read the contents of a spreadsheet (ODS)

PyUno is part of Apache OpenOffice.