Python,如何有单独的参数处理和主要功能?

时间:2013-12-21 03:12:28

标签: python namespaces

如果我有两个这样的defs:

def handle_args(argv=None) 
.
.
.

def main()
.
.
.

我如何让程序正文包括:

if __name__ == "__main__":
    handle_args(argv)
    main()

仍允许main访问参数,并允许handle_args()访问argv?

我当前的代码(我还没有测试过,我知道它错了,我还在试图破解它)是:

在文件ising.py中:

import extra,sys
global argv
def main(argv=None):

    print('test')


if __name__ == "__main__":
    extra.handle_args(argv)
    main()
    sys.exit(main())

在文件extra.py中:

'''
ising -- 3D Ising Model Simulator

ising is a ising model simulator for three dimensional lattices. It has four built in lattice structures
corespodinging to iron, nickel, cobalt and a generic lattice.

@author:     Joseph "nictrasavios" Harrietha
@copyright:  2013 Joseph Harrietha. All rights reserved.
@license:    GNU GPL3
@contact:    nictrasavios@gmail.com
'''
import sys,os,argparse

__all__ = []
__version__ = 0.1
__date__ = '2013-12-20'
__updated__ = '2013-12-20'


def handle_args(argv=None): # IGNORE:C0111
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    else:
        sys.argv.extend(argv)

    program_name = os.path.basename(sys.argv[0])
    program_version = "v%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
    program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
    program_license = '''%s

    Created by Joseph "nictrasavios" Harrietha on %s.
    Copyright 2013 Joseph Harrietha. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

USAGE
''' % (program_shortdesc, str(__date__))

    try:
        # Setup argument parser
        parser = argparse.ArgumentParser(description=program_license, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %(default)s]")
        parser.add_argument('-V', '--version', action='version', version=program_version_message)
        parser.add_argument("-f", "--field", dest="field",default=1, help="Set the value of the magnetic feild. [default: %(default)s]")
        parser.add_argument("-t", "--temp", dest="temp",default=1, help="Set the value of the temperature in Kelvin. [default: %(default)s]")
        parser.add_argument("-l", "--side", dest="side",default=1, help="Set the width/height of the square latice. [default: %(default)s]")
        parser.add_argument("-j", "--excont", dest="excont",default=1, help="Set the value of the Exchange Constant. [default: %(default)s]")
        parser.add_argument("-d", "--data", dest="data",default=10**3, help="Set the number of points to plot for time evolution. [default: %(default)s]")
        parser.add_argument("-m", "--steps", dest="steps",default=10**3, help="Sets the number of Monte Carlo steps. [default: %(default)s]")
        # Process arguments
        args = parser.parse_args()
        verbose = args.verbose

        if verbose > 0:
            print("Verbose mode on")

    except KeyboardInterrupt:
        return 0
    except Exception:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(Exception) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2

2 个答案:

答案 0 :(得分:1)

您的handle_argv函数可能应该以某种格式返回已解析的参数,其余代码可以使用。目前你正在返回某种整数错误代码,这不是非常恐怖的(并且你甚至不存储或检查该值)。

所以,我会做类似的事情:

import sys

def handle_argv(argv=None):
    if argv is None:
        argv = sys.argv

    # do your parsing here, and don't bother catching exceptions

    return args

def main(args):
    # do whatever, reading args as necessary

if __name__ == "__main__":
    args = handle_argv(sys.argv)
    main(args)

如果您想将handle_argv功能移动到另一个模块,则无需更改其他任何内容(只需导入模块并使用whateverthemoduleis.handle_argv(sys.argv)

答案 1 :(得分:1)

您可以尝试使用optparser

from optparse import OptionParser

def handle_argv():
    parser = OptionParser()
    parser.add_option("-u", "--url", dest="url",
                       help="Url to start crawl with")

    options, args = parser.parse_args()
    return options

def main():
    options = handle_argv()
    url = options.url
    print url

main()