2

I have started with python n flask few days ago. I was just trying to run a python file webapp.py on a terminal with following code but got errors:

$ ./webapp.py 
from: can't read /var/mail/flask
from: can't read /var/mail/flask
./webapp.py: line 3: syntax error near unexpected token `('
./webapp.py: line 3: `app = Flask(__name__)'

But it runs successfully with the command:

$ python webapp.py 
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat

webapp.py

from flask import Flask
from flask import render_template
app = Flask(__name__)


@app.route('/')
def home():
    return render_template('home.html')
if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

As a part of curiosity,

  • Whats the difference between ./webapp.py and python webapp.py?
Laxmikant
  • 2,046
  • 3
  • 30
  • 44

1 Answers1

2

When running a python script directly (without specifying the interpreter in the command), you need to tell the shell which interpreter will process the script, e.g.:

#!/usr/bin/env python
from flask import Flask
from flask import render_template

This first line is often referred to as "shebang".

MByD
  • 135,866
  • 28
  • 264
  • 277
  • 2
    Only a small extension. The file has to be executable: `chmod +x webapp.py`. When calling it like this: `python webapp.py`, it doesn't need to be executable. – cezar Oct 07 '15 at 06:37
  • 1
    Good point. Although it seems that the file is already an executable. – MByD Oct 07 '15 at 07:03