简体   繁体   中英

script file not found when using cmd.exe

I'm just getting started with Python and am trying to run a program from the command line, as it is done on this website under the heading "Python Program". So I made script hello.py, it's located in my computer at C:\Python27.

In the example, they run the script by typing python hello.py Guido . When I try to do this, it doesn't work. Firstly, I'm not entirely sure what is meant by the 'command line', but I'm using cmd.exe in Windows XP. I get this:

python: can't open file 'hello.py': [Errno 2] No such file or directory.

I have already specified PATH as C:\Python27.

Also, when I try to run the program from the Python shell by typing hello.py Guido I get

SyntaxError: invalid syntax.

You need to locate your cmd current directory at C:\\Python27 :

cd C:\Python27

because the path python loads is relative. You can also use a full path:

python C:\Python2.7\hello.py

When you start cmd.exe , the default directory is your Documents and Settings : since your file hello.py is not there, the python interpreter can't find it, thus giving you the [Errno 2] No such file or directory error. To solve that, just change your current working directory:

C:\Documents...>cd C:\Python27
C:\Python27> python hello.py Guido

Anyway, it is a good approach not to having your files inside the python directory (create a directory in your documents for python sources and use the same approach).

When you are running the python shell, you cannot explicitly call python files, so in your case it tries to run hello.py as a command (which doesn't exists) and it gives you a syntax error.

Try without "python", when you put python directory in path, it automatically connects ".py" extension with python, so there is no need in writing "python hello.py Guido"

Just go to directory where .py is located, and call "hello.py"

What's your current working directory and where is hello.py located? To execute that command, hello.py should be in the same directory from where you started the commend line (cmd.exe). Otherwise you need to the write the absolute path of hello.py (like python C:.....\\hello.py Guido ) instead of just the filename 'hello.py'.

I had also this problem but because of ether reason: I accidently added spaces to the names of some of the file's names, so the CMD didn't recognized the names. for example: 'run.bat'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM