Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between __file__ and sys.argv[0]

Tags:

python

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.

like image 682
user225312 Avatar asked May 01 '11 21:05

user225312


2 Answers

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

like image 191
Sven Marnach Avatar answered Sep 18 '22 20:09

Sven Marnach


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.

like image 43
Achim Avatar answered Sep 21 '22 20:09

Achim