简体   繁体   English

python和sys.argv

[英]python and sys.argv

if len(sys.argv) < 2:
    sys.stderr.write('Usage: sys.argv[0] ')
    sys.exit(1)


if not os.path.exists(sys.argv[1]):
    sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
    sys.exit(1)

This is a portion of code I'm working on. 这是我正在研究的代码的一部分。 The first part I'm trying to say if the user doesn't type python programname something then it will exit. 第一部分我想说的是如果用户没有键入python programname something就会退出。

The second part I'm trying to see if the database exists. 第二部分我试图看看数据库是否存在。 On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not. 在这两个地方,我都不确定我是否有正确的方法来写出stderr或不是stderr的sys.argv。

BTW you can pass the error message directly to sys.exit: 顺便说一句,您可以将错误消息直接传递给sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. 在Python中,您不能只将任意Python表达式嵌入到文字字符串中,并将其替换为字符串的值。 You need to either: 你需要:

sys.stderr.write("Usage: " + sys.argv[0])

or 要么

sys.stderr.write("Usage: %s" % sys.argv[0])

Also, you may want to consider using the following syntax of print (for Python earlier than 3.x): 此外,您可能需要考虑使用以下print语法(对于早于3.x的Python):

print >>sys.stderr, "Usage:", sys.argv[0]

Using print arguably makes the code easier to read. 使用print可以说代码更容易阅读。 Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example. Python会自动在print语句的参数之间添加一个空格,因此在上面的示例中,冒号后面会有一个空格。

In Python 3.x, you would use the print function: 在Python 3.x中,您将使用print函数:

print("Usage:", sys.argv[0], file=sys.stderr)

Finally, in Python 2.6 and later you can use .format : 最后,在Python 2.6及更高版本中,您可以使用.format

print >>sys.stderr, "Usage: {0}".format(sys.argv[0])

I would do it this way: 我会这样做:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be. 如果需要,这允许将main()导入到其他模块中,并简化调试,因为您可以选择argv应该是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM