python - 命令行提示错误

标签 python command-line conditional-statements

我的程序需要 2 或 3 个命令行参数:

-s 是一个可选参数,表示稍后在我的程序中进行切换 -infile 是文件输入 -outfile为写入的文件

如果发生以下任何情况,我需要我的程序打印错误消息并退出:

  • 用户指定不以 .genes 结尾的内文件名称
  • 用户指定的输出文件名称不以 .fa 或 .fasta 结尾
  • 用户提供少于 2 个或多于 3 个参数
  • 用户的第一个参数以破折号开头,但不是“-s”

我写了:

def getGenes(spliced, infile, outfile):
spliced = False
if '-s' in sys.argv:
    spliced = True
    sys.argv.remove('-s')
    infile, outfile = sys.argv[1:]
if not infile.endswith('.genes'):
    print('Incorrect input file type')
    sys.exit(1)
if not outfile.endswith('.fa' or '.fasta'):
    print('Incorrect output file type')
    sys.exit(1)
if not 2 <= len(sys.argv) <= 3:
    print('Command line parameters missing')
    sys.exit(1)
if sys.argv[1] != '-s':
    print('Invalid parameter, if spliced, must be -s')
    sys.exit(1)

但是,某些条件与某些条件发生冲突,包括第一个和最后一个条件是矛盾的,因为 s.argv[1] 始终不等于 '-s',因为如果 's' 出现在 argv 中,它较早被删除。所以我不知道如何正确地写这个......

最佳答案

sliced=False 未缩进

def getGenes(spliced, infile, outfile):
     spliced = False

sys.argv.remove('s') 它应该是 sys.argv.remove('-s')

两个条件相互矛盾:

if '-s' in sys.argv:
    spliced = True
    sys.argv.remove('-s') # you removed '-s' from sys.argv ,so the below if condition becomes false
    infile, outfile = sys.argv[1:]  

if sys.argv[1] != '-s':
    print('Invalid parameter, if spliced, must be -s')
    sys.exit(1)

代码的编辑版本:

import sys

def getGenes(spliced, infile, outfile):
 spliced = False
if '-s' in sys.argv:
    spliced = True
    infile, outfile = sys.argv[2:]
if not infile.endswith('.genes'):
    print('Incorrect input file type')
    sys.exit(1)
if not outfile.endswith('.fa' or '.fasta'):
    print('Incorrect output file type')
    sys.exit(1)
if not 3 <= len(sys.argv) <= 4:
    print('Command line parameters missing')
    sys.exit(1)
if sys.argv[1] != '-s':
    print('Invalid parameter, if spliced, must be -s')
    sys.exit(1)

关于python - 命令行提示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10306018/

相关文章:

command-line - 如何在 Fedora 19 中通过命令行生成数据库图表?

java - 如何读取java中的脚本输出?

python - 列表理解转换

python - 为什么我需要带 time() 的 round() 函数?

python - 如何将两个后续事件绑定(bind)到 python 中的一个回调?

python - Flask API 错误 JSONDecodeError ("Expecting value", s, err.value) None json.decoder.JSONDecodeError : Expecting value: line 1 column 1 (char 0)

linux - 从 kra 导出一个 png,一个 krita 文件

python - 线程和条件

mysql - 使用迭代器删除 MySQL 表

mysql - 有条件选择