32

Is there any difference between:

__file__

and

sys.argv[0]

Because both seem to be doing the same thing: they hold the name of the script.

If there is no difference, then why is it that __file__ is used in almost all someplaces whereas I have never seen sys.argv[0] being used.

user225312
  • 126,773
  • 69
  • 172
  • 181

5 Answers5

27

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

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
6

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.

tzot
  • 92,761
  • 29
  • 141
  • 204
Achim
  • 15,415
  • 15
  • 80
  • 144
3

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.

Lumi
  • 14,775
  • 8
  • 59
  • 92
  • Ludwig: Probably you should do some more experimentation. Create an empty file named `empty.py`. At the Python interactive prompt, enter this line: `import empty; print(empty.__file__); reload(empty); print(empty.__file__)` ... then edit your answer. – John Machin May 01 '11 at 22:48
  • Ludwig: Facts: `__file__` is an attribute of the module, created automatically when the module is loaded. CPython doesn't have a preprocessor step. – John Machin May 01 '11 at 23:46
0

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

Stanislav Ageev
  • 778
  • 4
  • 10
0

You can detect whether your *.py code is running as a module or as the main script!

__file__ is the current file which may be inside a module and not the main script, which is called sys.argv[0].

It's useful because you can have code, like a main block, tests, etc. in a file that only runs if it's NOT being used in a module aka it's the main script

if __file__.endswith(sys.argv[0]):
    #you're the main script
chad steele
  • 828
  • 9
  • 13