gpt4 book ai didi

Python,如何有单独的参数处理和主函数?

转载 作者:行者123 更新时间:2023-12-04 17:00:32 26 4
gpt4 key购买 nike

如果我有两个这样的定义:

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

最佳答案

可能是你的 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)

关于Python,如何有单独的参数处理和主函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20715013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com