Python recipes: Difference between revisions

From Wildsong
Jump to navigationJump to search
Brian Wilson (talk | contribs)
mNo edit summary
 
Brian Wilson (talk | contribs)
 
(9 intermediate revisions by the same user not shown)
Line 1: Line 1:
The script so far:
Here are code snippets I can't seem to keep in my head between uses.


<pre>
=== Simple file reader ===
# ---------------------------------------------------------------------------
# StructId.py
# Created on: Tue Feb 14 2006 05:06:58 PM
#  (generated by ArcGIS/ModelBuilder)
# ---------------------------------------------------------------------------


# Import system modules
with open(filename) as fp:
import sys, string, os, win32com.client
  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


# Create the Geoprocessor object
=== Redirect stdout ===
gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1")


#
import sys
gp.workspace = "H:/BrianWilson/Workspace/Collections/Collections.mdb/Collections"
save_stdout = sys.stdout
out_workspace = "C:/Temp/NewShapefiles"
sys.stdout = open('file', 'w')
print 'test'
sys.stdout = save_stdout


# Load required toolboxes...
=== Writing a log ===
#gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")


# Process: Calculate Field...
=== Date stamps ===
# the expressions here can only be very simple.
# You can use variables in [square brackets], you can use constants, and you can use
# simple operators like + - / * and (for strings) &
# manhole_shp = "C:\\TEMP\\NewShapefiles\\manhole.shp"
#gp.CalculateField_management(manhole_shp, "STRUCT_ID", "[STRUCT_TYP]&\"-\"& [MH_LABEL]")


# Export all the feature classes from our geodatabase to individual shapefiles
from datetime import datetime
fcs=gp.ListFeatureClasses()
fcs.reset()
datetime.now() # returns an object
fc=fcs.Next()
datetime.datetime(2015, 12, 2, 12, 0, 28, 8580)
while fc:
    output_shapefile = out_workspace + '/' + fc
datetime.now().strftime("%Y-%m-%d %H:%M") # returns a formatted string like '2015-12-02 12:01'
    gp.AddMessage("Working on " + fc + "...")
    gp.FeatureClassToShapefile_conversion(fc, out_workspace)
    fc = fcs.next()


# Rename the new shapefiles to their correct GISMO names
=== Running commands ===
Run a process and watch its return code.
  import subprocess
  try:
    retcode = subprocess.call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode)
    else:
        print("Child returned", retcode)
  except OSError as e:
    print("Execution failed:", e)


# Calculate the missing field values
Run a command and fetch its output


# Delete the fields that don't belong in GISMO output
  output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].splitlines()
</pre>
 
=== Read the contents of a spreadsheet (ODS) ===
 
PyUno is part of Apache OpenOffice.

Latest revision as of 02:17, 13 March 2023

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

Run a process and watch its return code.

 import subprocess
 try:
   retcode = subprocess.call("mycmd" + " myarg", shell=True)
   if retcode < 0:
       print("Child was terminated by signal", -retcode)
   else:
       print("Child returned", retcode)
 except OSError as e:
   print("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.