Question

I do not really understand the difference between using if __name__ == '__main__' and just making file executable. I need to make sure that the same file will run both on Linux and Windows. I am working on Linux. I tried to use if __name__ == '__main__ for this but it does not work. Can anyone advise how to make code work on both Linux and Windows.

Structure of my project:

-test(project) -test(folder-python package) -static dir -templates dir -__init__.py -methods.py -views.py -mydatabase.py -runserver.py

Here is code:

init.py

from flask import Flask
application = Flask(__name__)
application.config.update(DEBUG=True,SECRET_KEY='key')

import view

runserver.py

#!/usr/bin/python
from test import application
application.run()

and then from terminal I run

path/to/file/ ./runserver.py

It works perfect on Linux. But I need to give this code to people who might use it on Windows. So to make sure it will work, I tried to do this:

I created file runapp.py inside package:

-test(project)
 -test(folder-python package)
   -static dir
   -templates dir
   -__init__.py
   -methods.py
   -views.py
   -mydatabase.py
   -runapp.py

Took away all code from init.py and runserver.py and put in runapp.py this code:

runapp.py

from flask import Flask

application = Flask(__name__)#instance of WSGI application
application.config.update(DEBUG=True,SECRET_KEY='hello123')

import view

if __name__ == '__main__':
    application.run()

After this tried to run it from terminal:

path/to/file python runapp.py

but got ImportError: No module named flask

Obviously I am doing something wrong or dont understand how to use if __name__=='__main__'

I will really appreciate advice on how to make file executable on Linux and Windows simultaneously.

Was it helpful?

Solution 2

I found the answer on my question.

I left everything as it was (with init.py, runserver.py) and tried it on Windows.The only difference in running code on Linux and Windows is:

runserver.py

#!/usr/bin/python
from test import application
application.run()

on Linux make fiel executable with chmod +x runserver.py

and then in terminal: path/to/file ./runserver.py

on Windows in cmd: path/to/file python runserver.py

It works just fine on both OS. Thanks to everyone.

OTHER TIPS

You don't have installed flask at a place, where python looks for it. This has nothing to do with the name-main-thing.

With if __name__=='__main__' you can use python-files as modules and as main-application files. It allows you to import the file for testing or for reusing functions and classes.

You can see this extension for do most professional this process.

http://flask-script.readthedocs.org/en/latest/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top