做新旧命令兼容的一种方式

将无法解析的命令
1. catch parse异常.
2. 错误输出直接重定向/dev/null.避免干扰output

#!/usr/bin/env python

import sys
import os
import subprocess
from optparse import OptionParser

class redirect_stdout_stderr(object):
    def __init__(self, stream):
        # Save the old std streams
        self.old_stream = sys.stdout
        self.old_error_stream = sys.stderr
        self.fstream = stream

    def __enter__(self):
        # Change the std streams to your streams when entering
        sys.stdout = self.fstream
        sys.stderr = self.fstream

    def __exit__(self, exc_type, exc_value, exc_traceback):
        # Change the std streams back to the original streams while exiting
        sys.stdout = self.old_stream
        sys.stderr = self.old_error_stream

if __name__ == "__main__":
    usage = "mdfscli [options]"
    parser = OptionParser(usage)
    #需要兼容的旧命令
    parser.add_option("--build-info", action="store_true", dest="cmd_build_info", \
                      default=False, help="Show build information")
    newappcli = ""
    try:
        # parse command line arguments
        with redirect_stdout_stderr(open(os.devnull, 'w')):
            (options, args) = parser.parse_args()
    except:
        newappcli = "/usr/share/yourapp/newappcli %s" % (" ".join(sys.argv[1:]))
    else:
        if options.cmd_build_info:
            newappcli = "/usr/share/yourapp/newappcli --build-info"
        else:
          newappcli = "/usr/share/yourapp/newappcli %s" % (" ".join(sys.argv[1:]))

    cmd = subprocess.Popen(newappcli, shell=True, stdout=sys.stdout, stderr=sys.stderr, close_fds=True)
    sys.exit(cmd.wait())
Published
Categorized as py

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.