You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.2 KiB
Python

6 years ago
import os
import subprocess
def call_lastools(tool_name, input, output=None, args=None, verbose=True):
6 years ago
"""Send commands to the lastools library.
Requires lastools in system path.
Args:
tool_name: name of lastools binary
input: bytes from stdout, or path to main input data
output: '-stdout' to pipe output, or path to main output data
6 years ago
args: list of additional arguments, formatted for lastools
verbose: show all warnings and messages from lastools (boolean)
6 years ago
Returns:
bytes of output las, if output='-stdout'
None, if output='path/to/las/file'
6 years ago
Examples:
# Convert xyz file to las and pipe stdout to a python bytes object
las_data = call_lastools('txt2las', input='points.xyz', output='-stdout',
6 years ago
args=['-parse', 'sxyz'])
# Clip las_data with a shapefile, and save to a new las file
call_lastools('lasclip', input=las_data, output='points.las',
6 years ago
args=['-poly', 'boundary.shp'])
"""
# Start building command string
cmd = [tool_name]
# Parse input
if type(input) == bytes:
6 years ago
# Pipe input las bytes to stdin
cmd += ['-stdin']
stdin = input
6 years ago
else:
# Load las from file path
cmd += ['-i', input]
6 years ago
stdin = None
# Parse output
if output == '-stdout':
6 years ago
# Pipe output las to stdout
cmd += ['-stdout']
elif output:
6 years ago
# Save output las to file
cmd += ['-o', output]
6 years ago
# Append additional lastools arguments, if provided
if args:
cmd += args
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stdout, stderr = process.communicate(input=stdin)
# Handle errors, if detected
if process.returncode != 0:
print("Error: {} failed on {}".format(tool_name,
os.path.basename(input)))
6 years ago
print(stderr.decode())
elif verbose:
# Print addional messages if verbose mode is being used
print(stderr.decode())
6 years ago
# Output piped stdout if required
if output == '-stdout':
6 years ago
return stdout
else:
return None