使用sys.argv []调用Python 3.x调用函数

时间:2011-06-23 20:59:38

标签: python python-3.x

我有一个处理文件内容的函数,但是现在我将函数中的文件名硬编码为关键字参数:

def myFirstFunc(filename=open('myNotes.txt', 'r')): 
    pass

我称之为:

myFirstFunc()

我想将参数视为文件名并处理内容。

  1. 如何修改上述声明?我试过这个:

    filename=sys.argv[1]  # or is it 0?
    
  2. 我该怎么称呼它?

3 个答案:

答案 0 :(得分:8)

类似的东西:

#!/usr/bin/python3

import sys


def myFirstFunction():
    return open(sys.argv[1], 'r')

openFile = myFirstFunction()

for line in openFile:
    print (line.strip()) #remove '\n'? if not remove .strip()
    #do other stuff

openFile.close() #don't forget to close open file

然后我会像下面这样称呼它:

./readFile.py temp.txt

将输出temp.txt的内容

sys.argv[0]输出脚本名称。在这种情况下./readFile.py

更新我的答案
因为似乎其他人想要try方法

How do I check whether a file exists using Python? 关于如何检查文件是否存在的问题是一个很好的问题。关于使用哪种方法似乎存在分歧,但使用接受的版本将如下:

 #!/usr/bin/python3

import sys


def myFirstFunction():
    try:
        inputFile = open(sys.argv[1], 'r')
        return inputFile
    except Exception as e:
        print('Oh No! => %s' %e)
        sys.exit(2) #Unix programs generally use 2 for 
                    #command line syntax errors
                    # and 1 for all other kind of errors.


openFile = myFirstFunction()

for line in openFile:
    print (line.strip())
    #do other stuff
openFile.close()

将输出以下内容:

$ ./readFile.py badFile
Oh No! => [Errno 2] No such file or directory: 'badFile'

您可以使用if语句执行此操作,但我喜欢this评论EAFP VS LBYL

答案 1 :(得分:2)

对于Python 3,您可以使用上下文管理器。

# argv[0] is always the name of the program itself.
try:
    filename = sys.argv[1]
except IndexError:
    print "You must supply a file name."
    sys.exit(2)

def do_something_with_file(filename):    
    with open(filename, "r") as fileobject:
        for line in fileobject:
            do_something_with(line)

do_something_with_file(filename)

答案 2 :(得分:2)

这比你要求的要多,但这是我用来使用命令行参数的一个常用习惯用法:

def do_something_with_file(filename):    
    with open(filename, "r") as fileobject:
        for line in fileobject:
            pass    # Replace with something useful with line.

def main(args):
    'Execute command line options.'
    try:
        src_name = args[0]
    except IndexError:
        raise SystemExit('A filename is required.')

    do_something_with_file(src_name)


# The following three lines of boilerplate are identical in all my command-line scripts.
if __name__ == '__main__':
    import sys
    main(sys.argv[1:])  # Execute 'main' with all the command line arguments (excluding sys.argv[0], the program name).