Last active
August 29, 2015 14:02
-
-
Save hironow/f5e6f6fa2f8b2930a5b6 to your computer and use it in GitHub Desktop.
Using GMT from Python by subprocess and shlex packages (redirect).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import (absolute_import, division, | |
print_function, unicode_literals) | |
from future_builtins import * | |
import shlex | |
import subprocess | |
import os | |
class ScriptRunningError(Exception): | |
pass | |
def runScript(script): | |
""" Run shell script depend on os environ. | |
Can use writing and appending mode by redirect ('>' or '>>'). | |
:param str script: running script | |
""" | |
script_list = shlex.split(script) | |
if '>' in script_list: | |
# Writing mode | |
output_file = script_list[script_list.index('>') + 1] | |
script_pre = script_list[:script_list.index('>')] | |
with open(output_file, 'w') as f: | |
proc = subprocess.Popen(script_pre, env=os.environ, | |
stdout=f, stderr=subprocess.PIPE) | |
elif '>>' in script_list: | |
# Appending mode | |
output_file = script_list[script_list.index('>>') + 1] | |
script_pre = script_list[:script_list.index('>>')] | |
with open(output_file, 'a') as f: | |
proc = subprocess.Popen(script_pre, env=os.environ, | |
stdout=f, stderr=subprocess.PIPE) | |
elif ('>' in script) or ('>>' in script): | |
raise ScriptRunningError("Please insert a space before and after" | |
" the redirect $ %s" % str(script)) | |
else: | |
proc = subprocess.Popen(script_list, env=os.environ, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE) | |
# stdout and stderr simply wait for script | |
stdout, stderr = proc.communicate() | |
retcode = proc.returncode | |
del proc | |
if retcode == 1: | |
raise ScriptRunningError('This script could not run $ %s\n%s' % ( | |
str(script), str(stderr))) | |
else: | |
return True | |
if __name__ == '__main__': | |
script = "gmt --version > sample.txt" | |
runScript(script) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5.1.1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment