Start Python tutorials but have questions for beginners

advertisements

Hello I am attempting to learn Python using django in powershell on windows to create a simple CRUD app but have some questions regarding the setup and usage.

I have setup the path environment variable to include paths to a folder that includes test .py scripts that I thought allowed me to run directly from a c:\ in powershell but when I try to run the samples using:

c:\> python test1.py
c:\> python .\test1.py

It does not work and I get:

c:\Python27\python.exe: can't open file '.\test1.py':[Errno 2] No such file or directory

but if I CD to path first and run it works fine and I get the output in the powershell window itself:

c:\> cd c:\Python27\Scripts
c:\Python27\Scripts> python test1.py

In addition if I just type the name of the script from the root c:\ prompt such as:

c:\> c:\Python27\Scripts\test1.py
c:\> test1.py

it runs the script by opening in a dos box that that closes immediately since it ran the script and finished.

What is the difference between these methods and is there an issue running scripts one way or the other?


The issue here is that in the first case:

c:\> python test1.py
c:\> python .\test1.py

You're running python itself, and then the file is an argument to the interpreter. So python will be affected by PATH, but the file is relative. Both of these file paths mean to look for it in the same directory, which is the root of C:. Since the file isn't located there, the error results.

The second case:

c:\> c:\Python27\Scripts\test1.py
c:\> test1.py

It's the file itself being run as an "executable", factoring in PATH. On Unix, this would use the shebang and invoke the shell in pretty much the same way, however that's not the case on Windows. Instead, it's basically running whatever is associated with the .py extension at the OS level, which is likely to invoke a new Python interpreter in a new Window, hence the behavior where it disappears after it's done.

On Windows, since there's no shebang, I generally prefer to run the python interpreter directly and pass the script as an argument. I would generally switch to the directory the script is located in first. This way it's more shell-centric, and, I think, straightforward.

You can run pushd . to save the cwd, and then after popd to go back, optionally. That would work in .cmd files and similar, too.