How does python know to run from the command line? - python

Hi I noticed that whenever from the command line (using windows 8.1) I type
python file.py
It automatically knows that I meant to write python.exe file.py
How does it do this?
I installed Anaconda, and I understood I have an environment variable pointing to python.exe. But that doesn't explain why I need not type python.exe everytime.

This is not a python feature. The behavior to call executables without file extension is defined by the operation system and the PATH variable. Wikipedia has a good answer to your question
PATH (variable)
...
When a command is entered in a command shell or a system call is made by a program to execute a program, the system first searches the current working directory and then searches the path, examining each directory from left to right, looking for an executable filename that matches the command name given.
...
The file name after the executable could be everything. So if you want you can call python demo.txt. If the file content is readable for python it would also be executed.

Python is searched for using the path. Find the PATH in the list of environment variables.
If you do not write python and simply double-clicks the file, the registry is searched.
You can see what and associate files with program using ftype and assoc from the command line. See e.g. http://www.fileformat.info/tip/microsoft/assocftype.htm
If you omit the extension the registry is also searched. This cmd shell searches the environment variable PATHEXT and the registry for finding python.exe. After this, it is using the registry to find the location.
When you register your python distribution from within Spyder, these changes are made.
You can reveal this information by using ftype and assoc like I wrote in the beginning.

Related

Can I use a custom command in the CMD to run python script?

I would like to run my python script by a custom command
Previously, we would have to run
python hello.py
For example, I would type:
hello
in my command prompt
then my computer will run my hello.py
You can create a simple batch file and place it in a folder that is in your system path variable.
Name it $Py.bat
#Echo off
If not "%~1" == "" (
python "%~1.py" 2> nul || (Echo/"%~1.py" failed to execute correctly or was not found.)
) Else Echo/Filename required.
Then run it in cmd.exe using:
$Py hello
Another approach would to be to create a macro using setx
SetX run "python F.py"
SetX adds the variable with it's value to the registry. It is not available in the Session in which it is created, nor in any child environment of that Session.
Execute by expanding the variable with substring modification replacing F with the filename:
%run:F=hello%
There are two pieces to this. The first is the PATHEXT environment variable that stores a list of the file extensions for operation system to execute. When running a command line that does not contain an extension, the system uses the value of this environment variable to determine which extensions to look for and in what order, such as .com first, follow by .exe, .bat, .cmd, which happens to be the default value stored in the PathExt by Windows. On my computer:
C:\>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.py;.pyw
If .py is not part of your PATHEXT environment variable, you can add it by right-mouse clicking on the Start box in the lower left corner of your screen and the clicking on Settings. When the new window comes up, type environment in the search box and then click on one of the Edit choices:
This now allows you to type in hello instead of hello.py at the command prompt. Referring back to my environment variable, if there were two files hello.bat and hello.py the system would choose hello.bat because the .BAT extension is listed before the .py extension (everything is case insensitive). But the second piece of the puzzle is associating the Python interpreter with the .py extension so that the system knows how to run that type of file. Enter the Windows ftype command. This produces a list of mappings of file type extensions and the programs used to launch those extensions. On my computer, one of the lines listed is:
Python.CompiledFile="C:\WINDOWS\py.exe" "%L" %*
I installed Python using a standard installation from python.org and when I did I installed the optional Python launcher for Windows, which is the "C:\WINDOWS\py.exe" you see above. This launcher supports multiple Python versions and allows you to control which Python version will execute your Python program based on the shebang that you code as the first line of your program. But generally, when you install Python under Windows, an association is made between the .py file type and the Python interpreter. If you do not have this association, you can look for your Python file in an Explorer window, right-mouse click on it and then choose Open With:
My options show Python since I already have the association. In your case it would probably be missing, so you would pick "Choose Another App" and then if you still don't see Python in the list you would choose "Look for another app on this PC" and then navigate to the Python interpreter. Either way, be sure to click on the box labeled "Always use this app to open .py files":

Python directory conflicts with python executable location

I have a python executable I wish to run from PowerShell using the command python [executable].py.
First I changed the directory in PowerShell to the location of the executable using cd path\to\my\directory which worked fine. However whenever I tried to use python to execute my code, PowerShell immediately searches for the [executable].py in Python's installation folder - fails to find it - and gives the an error that it cannot find the appropriate file.
How do I make sure that Powershell looks for the executable in the directory I indicated as opposed to the default Python installation folder?
If you want to run python.exe from a location other than the installation directory you'd call it with its full path:
& 'C:\path\to\python.exe' 'your.py'
If you want to run it from the current directory, prepend the filename with the relative path .\:
& .\python.exe 'your.py'
If you call an executable without a path like this:
& python.exe 'your.py'
PowerShell will look for a matching file in the directories listed in the $env:PATH environment variable, and execute the first match (or report an error if no matching file can be found).
With that said, the error you got in your screenshot is not because of the Python interpreter, but because of the file you want the interpreter to run. You're calling
python conditions
when you actually want to run
python conditions.py
Neither PowerShell nor Python magically add the extension for you. Instead they report an error because a file conditions (without an extension) simply doesn't exist.

Trying to access Python through Windows Command Prompt without adding Environment Variable

I am trying to access Python through a Windows command prompt, but am at an office and cannot add an Environment Variable. So, I cant follow the advice provided here. Thus, I added a User Environment Variable through User Accounts and use Variable:python and Value: C:\Python33. When I do a Windows Run check on %python% I reach the required Python33 folder. However, when I type python -Version in the command prompt I get the error 'python' is not recognized as an internal or external command, operable program or batch file. I am not sure how to proceed.
Run Python from the command prompt and include the full path to python.exe. For example to get the version:
C:\Python33\python.exe --version
When you run a script you specify the path to the script if you're not in the directory where the script is located. For example, if your script is in C:\scripts and is called my_script.py:
C:\Python33\python.exe C:\scripts\my_script.py
Instead of setting environment variables, you can use the whole path, like Neo wrote e.g.:
C:\Python33\python.exe yourPythonScript.py
Remove any environment variables you have added.
C:\Python33\python.exe pyscript.py should work.
I once Had a similar problem, but i couldnt find any solution, not even adding the path to the python folder was working.
Then I opened Python and clicked in File, then browser path, and I found that I had another folder that contained the real Python folder, not the default one. Maybe it could work for you too.

How do I run a .py script directly from cmd?

Suppose I have a script called 'run.py', how can I do this?
C:\Users\Administrator>run
And this script will be executed. Please notice that I don't want a '.py' shown after 'run'.
I am using python 3.3.5, and I tried putting 'C:/python33' into environment variable path. But it didn't work.
It seems like it only works when it's a '.exe' file.
Thanks in advance.
You will need to add .py to your PATHEXT environment variable.
From the Python on Windows FAQ, How do I make Python scripts executable?
On Windows, the standard Python installer already associates the .py
extension with a file type (Python.File) and gives that file type an
open command that runs the interpreter (D:\Program
Files\Python\python.exe "%1" %*). This is enough to make scripts
executable from the command prompt as ‘foo.py’. If you’d rather be
able to execute the script by simple typing ‘foo’ with no extension
you need to add .py to the PATHEXT environment variable.
The exact method for setting environment variables varies with different versions of Windows, but this link can probably help you out.

Popen with conflicting executable/path

I'd like to call the "convert" utility from ImageMagick from my Python script using Popen, like so:
Popen(["convert", input_path, "-flop", output_file_path])
(The above example simply reverses the image horizontally)
The problem is that when I run the script in Windows, it mistakenly calls the convert.exe utility that ships with Windows to convert FAT partitions to NTFS! (located in \Windows\system32)
Now, if I randomly open a command prompt at any directory other than system32, and type "convert", it correctly runs the ImageMagick executable. So, this implies that Popen is automatically looking in system32. How can I make it not look in system32, and run the correct executable?
Search for a program is not trivial. I'd specify the full path to the convert.exe executable explicitly instead.
subprocess uses CreateProcess on Windows that looks in system32 directory even before any other directory in %PATH%:
... If the file name does not contain an extension, .exe is appended.
Therefore, if the file name extension is .com, this parameter must
include the .com extension. If the file name ends in a period (.) with
no extension, or if the file name contains a path, .exe is not
appended. If the file name does not contain a directory path, the
system searches for the executable file in the following sequence:
The directory from which the application loaded.
The current directory for the parent process.
The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory.
The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable. Note that this function does not search the per-application path specified by the App Paths registry key. To include this per-application path in the search sequence, use the ShellExecute function.
Therefore convert is equivalent to convert.exe in this case. It first looks in a directory that contains sys.executable e.g., C:\Python27. Then in the current directory: where you started the Python script from. Then in system32 where it finds convert.exe (filesystem utility, not imagemagick).
You could try to remove system32 directory from os.environ['PATH'] it may(?) suppress checking it: Popen(cmd, env=no_system32_environ) but it is fragile (worse than the explicit path).
There is a related issue on Python bug tracker: "Subprocess picks the wrong executable on Windows."
cmd.exe (the shell) uses different algorithm. See How does Windows locate files input in the shell?
If you set shell=True then the search sequence for convert program:
convert is not an internal shell command
there is no explicit path, so the search continues
search the current directory
search each directory specified by the PATH environment variable, in the order listed
%PATHEXT% defines which file extensions are checked and in what order e.g., convert.com, convert.exe, convert.bat, convert.cmd if %PATHEXT% is .com;.exe;.bat;.cmd.
As a completely different approach, you may want to try out PythonMagick, a Python wrapper for ImageMagick. This way you can access convert's functions from within Python, and you won't have to spawn outside processes.
Just ran into this myself. Running a php script in a shell has access to the shell $PATH, while running within Apache does not (at least not a $PATH with the Cygwin dll/exe).
Secondly, use the native Windows notation C:/dir/subdir/pgm within php when on a windows platform and you will get what you expect.
So multi-platform code needs to switch/case the pathing and then reference the decision.

Categories

Resources