Scott Schupbach Scott Schupbach - 9 days ago 8
Python Question

Python equivalent of Ruby `if __FILE__ == $PROGRAM_NAME`

In Ruby, you can write a class/module such that it can be (a) loaded into an interactive Ruby terminal without actually executing code, or (b) run as a shell script.

For example, given file

foo.rb
:

class Foo
def bar
puts 'Foo bar'
end
end

if __FILE__ == $PROGRAM_NAME
foo = Foo.new
foo.bar
end


This would load the
Foo
class for use in
irb
or
pry
, but wouldn't execute the instantiation of
foo
or the method call
foo.bar
inside the
if
statement at the end.

But if run in the command line with
ruby foo.bar
it would return
"Foo bar"
and exit.

Is there a Python (v2 or v3) equivalent of this?

The closest I've come (in 2.7) is this, but I feel like there might be a cleaner way:

import os, sys

if os.__file__ == sys.argv[0]:
# do stuff


(The JavaScript version of this question was moved here.)

Answer

In your example, when you are running a file independantly vs a part of a module, you can do something like this:

if __name__ == "__main__":
  main()

which will run main() if the python file is executed independently.

In your example, you would likely want something like this.

class Foo:
  def bar(self):
    print 'Foo bar'

def main():
  foo = Foo()
  foo.bar()

if __name__ == "__main__":
  main()

I personally like to define a main function as the above example, but could easily just do:

if __name__ == "__main__":
  foo = Foo()
  foo.bar()