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

6 投票
3 回答
27910 浏览
提问于 2025-04-16 20:11

我有一个函数用来处理文件内容,但现在我在函数里直接写死了文件名,像这样作为一个关键字参数:

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

然后我这样调用它:

myFirstFunc()

我想把这个参数当作文件名来处理内容。

  1. 我该怎么修改上面的语句?我试过这样:

    filename=sys.argv[1]  # or is it 0?
    
  2. 那我该怎么调用它呢?

3 个回答

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).
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)
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的方法

如何用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语句来做到这一点,但我更喜欢这个关于EAFP和LBYL的评论

撰写回答