[Tutor] unable to run file though dir path included

Steven D'Aprano steve at pearwood.info
Wed Dec 7 17:33:54 CET 2011


surya k wrote:
> I have included the path directory of the file but still I couldn't run it!.
> 1. I created a .pth file and wrote all required path list's and saved in "site-packages" of python dir.( python\Lib\Site-packages).
> 2. I also included python path ( c:\python27\) in system path so as to run it using command prompt.
> Now when I use this command to run a file "foo.py" at command prompt ( run>cmd )
> command: "python foo.py".. it isn't running.
> The following error is shown.
> " python: can't open file 'foo': [ Errno 2] no such file or directory".


That error shows that you are NOT calling "python foo.py", as you should, but 
are calling "python foo".

Notice that if the file is missing, the error message prints the file name you 
give on the command line:

[steve at orac ~]$ python foo.py
python: can't open file 'foo.py': [Errno 2] No such file or directory


(1) Inside the Python environment, you import modules by giving the bare name 
*without* the file extension:

import foo  # correct
import foo.py  # incorrect

The import command will search sys.path for the module. sys.path is 
initialised in part from the environment variable PYTHONPATH and from any .pth 
files visible to Python.


(2) Outside of Python, you are dealing with the command shell, and the command 
shell rules apply. The PATH (not PYTHONPATH) tells your shell where to find 
.exe files, but not documents. So you must give the full path to the file:

python C:\subdirectory\spam\ham\foo.py

or you must give a relative path starting from the current working directory:

python ..\ham\foo.py

In either case, you *must* give the file extension.


(3) The third option is to combine the best of both, by using the -m switch 
which instructs Python to search the PYTHONPATH for the named module and then 
execute it:

python -m foo




-- 
Steven



More information about the Tutor mailing list