Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用sys.argv[]调用Python3.x函数_Python_Python 3.x - Fatal编程技术网

使用sys.argv[]调用Python3.x函数

使用sys.argv[]调用Python3.x函数,python,python-3.x,Python,Python 3.x,我有一个处理文件内容的函数,但现在我在函数中硬编码了文件名,如下所示,作为关键字参数: def myFirstFunc(filename=open('myNotes.txt', 'r')): pass 我这样称呼它: myFirstFunc() #!/usr/bin/python3 import sys def myFirstFunction(): return open(sys.argv[1], 'r') openFile = myFirstFunction()

我有一个处理文件内容的函数,但现在我在函数中硬编码了文件名,如下所示,作为关键字参数:

def myFirstFunc(filename=open('myNotes.txt', 'r')): 
    pass
我这样称呼它:

myFirstFunc()
#!/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
我想将参数视为文件名并处理其内容

  • 如何修改上面的语句?我试过这个:

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

  • 大概是这样的:

    myFirstFunc()
    
    #!/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 badFile
    Oh No! => [Errno 2] No such file or directory: 'badFile'
    
    /readFile.py temp.txt

    它将输出temp.txt的内容

    sys.argv[0]
    输出脚本的名称。在本例中,
    /readFile.py

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

    这是一个关于如何检查文件是否存在的好问题。对于使用哪种方法似乎存在分歧,但使用公认的版本时,应如下所示:

     #!/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的评论,对于Python3,您可以使用上下文管理器

    # 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)
    

    这超出了您的要求,但这里有一个我用于使用命令行参数的常用习惯用法:

    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).
    

    要添加的注意事项-从命令行检索输入时应小心。如果参数不是文件的有效路径怎么办?如果没有争论怎么办?对于这个快速的例子来说,这并不重要,但是在测试和未来的工作中记住这一点是很好的。我必须同意Doug的观点。我会在生产中做一些不同的事情,但这可能足以解决这个问题。任何更多的事情都可能分散对眼前问题的注意力。但是,如果这是一个简单的文本处理的个人需要,这应该是所有你需要的。也同意。这不仅仅是为了以后指出这一点。这似乎不像是需要添加的另一个答案:)不要像那样使用默认参数。即使从未调用该函数,它也会打开文件“myNotes.txt”。默认参数应该几乎总是不变的值。“我在函数中硬编码了文件名…”不,你没有;将文件对象本身指定为默认参数。这真是个坏主意。您希望将实际名称
    'myNotes.txt'
    传递给函数,而不是
    open()
    结果。让函数体执行
    open()
    操作。元组解包与注释中的代码并不完全相同,因为如果提供了多个参数,它将引发异常(这是一个很好的副作用,但会使给定的错误消息稍微不正确)。@Steve Howard,说得好。在有更多的命令行解析之前,我将关闭该代码。