Python命令行菜单
我正在尝试开发一个菜单,功能如下:
- 检查/tmp目录是否对运行脚本的用户有写入权限。
询问这个问题:你所有的本地仓库都在同一个地方吗?比如说 /home/joe/hg/(是/否)
如果回答是“是”,那么接着询问这些仓库的完整路径:- 把仓库的名字(连同它们的完整路径)存储在一个列表里。
- 把一些配置文件从目录 /tmp/hg-jira-hook-config/ 复制到所有的 "home/joe/hg//.hg/" 目录下。
- 给每个仓库的配置文件设置权限为755。
如果第二步的问题回答是“否”或者“NO”或者“no”,那么:
- 询问每个仓库的单独路径。
- 复制配置文件。
- 设置权限为755。
我有一个部分可用的脚本:
#!/usr/bin/env python
import sys,os
import stat
import tempfile
import shutil
__title_prefix = 'Python %i.%i.%i %s %s' % (sys.version_info[0:4] +
(sys.version_info[4] or "",))
if os.path.exists('/tmp'):
pass
else:
print '/tmp does not exist'
sys.exit()
def isgroupreadable(filepath):
st = os.stat(filepath)
return bool(st.st_mode & stat.S_IRGRP)
src = '/tmp/hg-jira-hook-config/' # This directory will be created as a result of apt-get install <package>
# and all config files will be copied
if isgroupreadable('/tmp'):
prompt_1 = ("Are ALL your LOCAL repositories in the same location? e.g. /home/joe/hg/<repo>[y/n], Press [q] when done\n")
answer_1 = raw_input(prompt_1)
if answer_1 == 'y' or None or 'YES' or 'yes':
while True:
answer_2 = raw_input("\n\nEnter the complete PATH of repos.Press [q] when done\n")
elif answer_1 == 'n' or 'NO' or 'No' or 'no':
result = raw_input("\n\nEnter the complete PATH of mercurial repositories you want this hook to be applied.Press [q] when done\n")
print result
else:
print 'cannot copy, wrong permissions on /tmp'
def main():
if __name__ == '__main__':
main()
测试运行:
python preinst
Are ALL your LOCAL repositories in the same location? e.g. /home/joe/hg/<repo>[y/n], Press [q] when done
y
Enter the complete PATH of repos.Press [q] when done
/home/joe/hg/app1
Enter the complete PATH of repos.Press [q] when done
/home/joe/hg/app2
Enter the complete PATH of repos.Press [q] when done
q
Enter the complete PATH of repos.Press [q] when done
所以问题是:
我该如何把路径存储在一个列表(或其他数据结构)中,以及如何让用户退出这个循环?
1 个回答
3
在所有情况下,用户至少需要提供一个程序的路径。直接在命令行上提供这个路径要简单得多(比如使用 argparse
),而不是去做一个复杂的交互式界面。而且,如果你使用像 argparse
这样的参数解析器,你的程序就可以很方便地被脚本化。相比之下,交互式程序的速度总是取决于用户的操作速度。因此,我几乎总是更喜欢可以脚本化的程序,而不是交互式程序。
下面是如何使用 argparse 来实现这一点:
import argparse
if __name__ == '__main__':
parser=argparse.ArgumentParser()
parser.add_argument('locations', nargs = '+')
args=parser.parse_args()
print(args.locations)
运行
% test.py /path/to/repo
['/path/to/repo']
% test.py /home/joe/hg /home/joe/test
['/home/joe/hg', '/home/joe/test']
argparse
也可以和交互式程序一起使用。例如,
import argparse
import shlex
response = raw_input('Enter repo PATHs (e.g. /path/to/repo1 /path/to/repo2)')
parser=argparse.ArgumentParser()
parser.add_argument('locations', nargs = '+')
args=parser.parse_args(shlex.split(response))
print(args.locations)
argparse
从 Python 2.7 开始就是标准库的一部分。如果你使用的是 Python 2.3 或更高版本,可以 安装 argparse。