背景资料
我正在编写一个python脚本,其中包含一组将通过命令行触发的方法。大多数函数将接受一个或两个参数。
问题
我一直在读关于ArgumentParser的文章,但我不清楚如何编写代码,以便使用“-”或“-”符号触发函数,并确保在调用特定函数时,用户传递的参数和类型的数量是正确的。
脚本中的示例函数:
def restore_db_dump(dump, dest_db):
"""restore src (dumpfile) to dest (name of database)"""
popen = subprocess.Popen(['psql', '-U', 'postgres', '-c', 'CREATE DATABASE ' + dest_db], stdout=subprocess.PIPE, universal_newlines=True)
print popen.communicate()
popen.stdout.close()
popen.wait()
popen = subprocess.Popen(['pg_restore','-U', 'postgres', '-j', '2', '-d', 'provisioning', '/tmp/'+ dump + '.sql' ], stdout=subprocess.PIPE, u
niversal_newlines=True)
print popen.communicate()
popen.stdout.close()
popen.wait()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--restore', dest='restoredbname',action='store_const', const=restore_dump, help='Restore specified dump file as dbname. Must supply <pathtodumpfile> and <dbname>')
args = parser.parse_args()
if __name__ == '__main__':
main()
帮助系统似乎正在工作,如下所示,但我不知道如何编写逻辑来强制/检查是否触发了“restore_dump”,用户正在传递正确的参数:
lab-1:/tmp# ./test-db.py -h
usage: test-db.py [-h] [-r]
optional arguments:
-h, --help show this help message and exit
-r, --restore Restore specified dump file as dbname. Must supply
<pathtodumpfile> and <dbname>
问题
至于如何“链接”-r参数以触发正确的函数,我在stackoverflow上看到了另一篇文章,所以我要检查一下。
谢谢。
编辑1:
我忘了说我正在读:
https://docs.python.org/2.7/library/argparse.html
但我不清楚如何将其应用到我的代码中。似乎在sum函数的情况下,参数的顺序是先是整数,然后是函数名。
在我的示例中,我希望首先使用函数名(作为可选参数),然后使用函数所需的参数。)
编辑2:
def main():
parser = argparse.ArgumentParser()
parse = argparse.ArgumentParser(prog='test-db.py')
parser.add_argument('-r', '--restore', nargs=2, help='Restore specified dump file as dbname. Must supply <pathtodumpfile> and <dbname>')
args = parser.parse_args()
if args.restore:
restore_db_dump(args.restore[0], args.restore[1])
if __name__ == '__main__':
main()
当我用一个丢失的参数运行它时,它现在正确地返回一个错误!太棒了!!!
但我想知道如何修复帮助,使之更有意义。似乎对于每个参数,系统都显示“RESTORE”一词。我该如何改变这一点,让它成为一个有用的信息?
lab-1:/tmp# ./test-db.py -h
usage: test-db.py [-h] [-r RESTORE RESTORE]
optional arguments:
-h, --help show this help message and exit
-r RESTORE RESTORE, --restore RESTORE RESTORE
Restore specified dump file as dbname. Must supply
<pathtodumpfile> and <dbname>