如果我有两个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
或者,如果你想成为面向未来的,使用[argparse(http://docs.python.org/2.7/library/argparse.html),其在所遇到的所有使用案例中,我发现远优于optparse。 – SethMMorton
我现在正在使用arg解析。 – NictraSavios