2013-12-21 43 views
0

如果我有两个DEFS像这样:Python,如何有独立的参数处理和主函数?

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: [email protected] 
''' 
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 

回答

1

可能是你handle_argv功能应该以某种格式的代码的其余部分可以使用返回解析参数。目前,您正在返回某种类型的整数错误代码,这并不是Pythonic的重要代码(并且您甚至不存储或检查该值)。

所以,我会做这样的事情:

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

你可以尝试使用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() 
+1

或者,如果你想成为面向未来的,使用[argparse(http://docs.python.org/2.7/library/argparse.html),其在所遇到的所有使用案例中,我发现远优于optparse。 – SethMMorton

+0

我现在正在使用arg解析。 – NictraSavios