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

pyt*_*gis 6 python python-3.x

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

def myFirstFunc(filename=open('myNotes.txt', 'r')): 
    pass
Run Code Online (Sandbox Code Playgroud)

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

  1. 我如何修改上面的语句 - 我试过这个: __CODE__
  2. 我怎么称呼它?

请帮助基础Python(刚刚学习)

谢谢

mat*_*hew 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
Run Code Online (Sandbox Code Playgroud)

然后我会把它称为如下:

./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()
Run Code Online (Sandbox Code Playgroud)

这将输出以下内容:

$ ./readFile.py badFile
Oh No! => [Errno 2] No such file or directory: 'badFile'
Run Code Online (Sandbox Code Playgroud)

你也许可以做到这一点有if声明,但我喜欢这种在EAFP VS LBYL评论

  • 添加到此的注释 - 从命令行检索输入时应该小心.如果参数不是文件的有效路径怎么办?如果没有参数怎么办?对于这个快速的例子来说无关紧要,但记住测试和未来的工作是件好事. (2认同)