When I run Python script from the command line
./file.py
it is interpreted differently(fails with a bunch of errors) from when I run it using:
python file.py
Why are they executed differently?
On Unix-like systems:
./file.py requires file.py to be executable (e.g., chmod a+x file.py)../file.py runs the script with whichever interpreter is specified in its shebang line; python file.py runs it with whichever interpreter named python is highest on your $PATH. If you have multiple versions of Python, this can make a big difference.If you don't know which python is highest on your $PATH, type which python and it will tell you.
If you want the shebang line to run the python that's highest on your $PATH, write it as:
#!/usr/bin/env python
On Windows:
./file.py runs the script with whatever application is registered to handle *.py files, whereas python file.py runs it with whichever interpreter named python.exe is highest on your %PATH%. Again, if you have multiple versions of Python, this can make a big difference.Note that Windows cmd.exe, unlike Unix shells, doesn't care about shebangs, only extensions. However, if you've installed a new enough version of Python, the application registered to handle *.py files will be the PEP 397 Python launcher, which does look at shebangs. (You can also get the launcher separately for older versions of Python.)
From your comments, the first line is:
just a start of the program, i.e. import socket
It sounds like you don't have a shebang line at all. That means that, if you're on a Unix-like system, ./file.py will run it with the default interpreter—which is /bin/sh on Unix and most Unix-likes, which isn't a Python interpreter at all. So you will probably get a bunch of confusing errors, probably starting with something like import: command not found.
which command to determine which python installation is the one that is highest on your $PATH. As you've stated in the answer already -- this is critical.python file.py was mandatory (except Python didn't exist then), and it felt like nothing less than a revolution when Unix allowed you to write new commands as scripts.sh (with functions and all), curses and termcaps, compress instead of pack, …
./file.pydo you expect the operating system to figure out that you actually wanted to executepython?.py, and Windows is almost an operating system. :) And even on many *nix systems, double-clicking the file in Finder/Nautilus/whatever will look at the extension.