Difference between __file__ and sys.argv[0]

后端 未结 4 533
面向向阳花
面向向阳花 2020-12-10 23:39

Is there any difference between:

__file__

and

sys.argv[0]

Because both seem to be doing the same thing: they hold

相关标签:
4条回答
  • 2020-12-11 00:25

    __file__ is the name of the current file, which may be different from the main script if you are inside a module or if you start a script using execfile() rather than by invoking python scriptname.py. __file__ is generally your safer bet.

    0 讨论(0)
  • 2020-12-11 00:25

    It's like Sven said.

    MiLu@Dago: /tmp > cat file.py
    import sys
    import blub
    print __file__
    print sys.argv[0]
    
    MiLu@Dago: /tmp > cat blub.py
    import sys
    print "BLUB: " + __file__
    print "BLUB: " + sys.argv[0]
    
    MiLu@Dago: /tmp > python file.py
    BLUB: /tmp/blub.pyc
    BLUB: file.py
    file.py
    file.py
    

    I thought that __file__ was replaced with the filename during a preprocessor step. I was not 100 % sure that's actually the case in Python - but it is in C/C++ and Perl. In Python, this might be different as the __file__ is also correct for compiled Python files (pyc), and there doesn't seem to be any trace of the filename in that file's contents.

    0 讨论(0)
  • 2020-12-11 00:26

    It's only the same if you are in the "main" script of your python programm. If you import other files, __file__ will contain the path to that file, but sys.argv will still hold the same values.

    0 讨论(0)
  • 2020-12-11 00:41

    Actually argv[0] might be a script name or a full path to the script + script name, depending on the os.

    Here's the entry in official documentation http://docs.python.org/py3k/library/sys.html#sys.argv

    0 讨论(0)
提交回复
热议问题