开发者

recursion with python argparse

I'm writing a recursive program using argparse. The only required argument is a file (or files) to act on. When I call it recursively, I don't need the filenames (as I'll be calling on a new directory), but i need the options. the problem is that argparse allows both python programname.py -options arg FILENAME FILENAME and python programname.py FILENAME FILENAME -options arg. I could painstakingly search for a '-' and work it out with a ton of if statements, but i feel like there should be a better way.

not sure that it matters, but here are my argparse declarations:

 parser = argparse.ArgumentParser(description='Personal upload script. (defaults to ' + user + '@' + server + directory + ')')
 parser.add_argument('files', nargs="+", help='file(s) to upload')
 parser.add_argument('-s', metavar='example.com', default=server, help='server to upload to')
 parser.add_argument('-u', metavar='username', default=user, help='ftp username')
 parser.add_argument('-p', metavar='password', default=password, help='ftp password')
 parser.add_argument('-d', metavar='example/', default=directory, help='directory to place file in')
 parser.add_argument('-n', metavar='myfile.txt', help='name to save file as')
 parser.add_argument('-c', metavar='###', help='chmod upload')
 parser.add_argument('-l', action='store_true', help='print out new url(s)')
 parser.add_argument('-r', action='store_true', help='recursive')
 parser.add_argument('-F', action='store_true', help='force (overwrite files / create non-existing dirs)')
 parser.add_argument('-v', action='store_true', help='verbose')
 args开发者_如何学C = parser.parse_args()

thanks so much!


You're just making life difficult for yourself. You don't make programs recursive, you make functions recursive. Making a program recursive is an excellent way to run out of memory and generally overwhelm a system.

Rewrite your application so that the recursive work is confined to a function that calls itself, instead of another instance of your application.

Or, better, eliminate recursiveness entirely. It looks like you're just iterating through a directory tree. There's no reason to do that recursively. In fact, Python has a library function that will take care of walking a directory tree for you. See os.walk.


You probably shouldn't be doing process-level recursion. That said, I think that argparse's treatment of "--" might provide the tool you're looking for (if I understand correctly). Search the argparse doc for the string "--".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜