我想制作一个Python模块,它可以被命令行和其他模块使用。 就像这样:
python3 Capacity.py arg1 arg2 arg3
or
>>> capacity.execByString("arg1 arg2 arg3")
我做了一个类(通过一些研究)在代码中获得argparse的结果:
class ArgumentParserError(Exception): pass
class Parseur(ArgumentParser):
def error(self, msg):
raise ArgumentParserError(msg)
def analyze(self, args):
if type(args) is not list:
args = args.split() # To work with a String
try:
result = self.parse_args(args)
return True, result
# Returns True and the namespace if OK
except ArgumentParserError as err:
return False, err.args[0]
# Returns False and the error message if not OK
我是这样用的:
class Capacity():
def __init__(self):
self.parser = Parseur()
# Config the parser
def execByArguments(*args):
# Do the job
def execByString(command):
isOK, result = self.parser.analyze(command)
if isOk:
# Launch execByArguments with the rights args in result
else:
# Print error message
print(result)
def execFromCommandLine():
args = self.parser.parse_args()
# Launch execByArguments with the rights args
if __name__ == "__main__":
execFromCommandLine()
但有两个主要问题,当然还有一些我还没有发现:
我确信把它变成另一个Parseur类是无用的/不好的,而且有一个解决方法。 通过子进程启动模块也不是一个好主意:在这种情况下,我希望获得返回的对象。 你能帮我找到一个很酷的方法来做我想做的事吗? 已经谢谢了。你知道吗
附言:在网上写代码是一件很痛苦的事。你知道吗
你不远了。我会这样做:
相关问题 更多 >
编程相关推荐