How CMD.exe recognize an extension need program? - python

When I give the path of a .py file to cmd.exe , It run that file automatically using Python.(I added the path of python to PATH Environment Variable already).
I want know:
1- how cmd.exe recognize that my .py file must run with python?
2- If I want to remove .py from the end of my file name, And replace it with .wxyz (for example), How I can make cmd.exe behave with that file such as a .py file? (In the other word I mean I want to add .wxyz extension to the list of files that run with python)

Windows keeps a list of file extensions and the programs that should run them. You can see the current list and add your own by going to the control panel, searching for "Default Programs" and selecting the entry that says something like "Make a file type always open in a specific program" (it varies by windows version and language of course).
Alternately, you can do it on the command line with the assoc and ftype commands. I don't have a windows machine up at the moment, but type these and see what you get.
assoc .py
ftype File.Python
This will get you the help on how to change them
assoc /?
ftype /?

1) There is a good explanation here:
When the Shell needs to query for the file associations of a file type, it creates an array of registry keys containing the associations for the file type, and checks these keys for the appropriate file associations to use.
In short, when you installed Python, it equipped Windows with enough context to know it should call for Python when it sees .py
2) A concise explanation is found here, with more context here.
In Windows this can be accomplished by editing the registry, allowing Windows to recognize custom extensions.

Related

How to run python scripts without typing python in windows

Let's say I have a python file named myfile.py in a certain directory.
How do I just call the python file directly without invoking python.
myfile.py
and not
python myfile.py
Edit:
To be more precise.
just typing the filename in the command line will not work.
Typing start program.py however should work.
Windows normally has information telling it which program is the default program for a given suffix.
Concerning #go2nirvan's comment: Though windows is not an oracle, it can have information for each file suffix to know what's the related default application.
Even many linux desktop application associate a default application to certain mime types.
If you click on .xls (depending on what is installed) either Excel, or OpenOfficeCalc or LibreOffice will be opened)
Windows associates file suffixes to file types and file types to applications, that are supposed to start it.
If you open a CMD window and you type
assoc .py
You should get an output similar to: (I don't have a windows machine nearby, so can't tell you the exact output)
.py=Python.File
Then type
ftype Python.File or whatever the previous command gave you and you should see which executable shall be used.
This should be something like
c:\System32\py.exe
which is a wrapper program, calling the real python executable according to some rules
If this doesn't work, then please tell which version of python you installed and how you installed it (for all users, for current user, ...)
From command line you have to call (If I recall correctly)
start test.py and it will execute the file with the associated executable
Windows
Set up Python on Windows to not type "python" in cmd
Linux
https://superuser.com/questions/828737/run-python-scripts-without-explicitly-invoking-python

Command prompt returning blank, but python console doesn't

Sorry if the title is a bit confusing; I'm not sure how to phrase it. I'm a beginner learning python for a linguistics course I'm taking, and I'm having a bit of a problem transferring some scripts into the command prompt. I'm using Windows 8.1 and python 3.6.0, if that helps at all.
The problem I'm having is that I can write a script in the python.exe program, and it will work exactly how it should. Then I will run the exact same script using the command prompt, the only thing it returns is a blank line.
for example, I can manually type this into the python console and get the right output:
>>>print("hello")
hello
but if I save that in a Notepad++ file and execute the same script using the command prompt, it'll look like this (please excuse my butchered pathway recreation):
C:\Users\username\Python>hello.py
C:\Users\username\Python>
The "hello.py" is the script I tried to run using the exact same code I manually entered in the Python console, but when I try to open the file, it does nothing.
This doesn't happen with every script I try to run, though, and I can't figure out what triggers this to happen. I'm not getting any kind of error, so I don't know how to go through trial and error. This is making it increasingly difficult to check my work as I add elements, and I'm not sure how to fix this. If anyone has suggestions, I would really appreciate the help.
Run Python scripts from Windows command line with script name only
Configure Windows File Association Pointers
Set the python.exe full explicit path as in the below #3 for the
correct value where this is on your system
Open up an elevated [cmd.exe] command prompt as administrator
Type in ASSOC .py=PythonScript and press Enter
Type in FTYPE PythonScript="C:\Program Files\Python\python.exe" "%1" %* and press Enter
Type in SET PATHEXT=.py;%PATHEXT% and press Enter
Execute from Shell with Script Name only
If you really need to run the script from the command line without telling the shell the full explicit path to the python script file, then you need to add the path where this script resides to the %PATH% environmental variable.
Open up an elevated [cmd.exe] command prompt as administrator
Type in SET PATH=%PATH%;C:\Program Files\Python where the C:\Program Files\Python is the value where this exist on your system.
Now you can just type in the script name with or without the file extension without doing a CD to another directory or explicitly specifying the full path to the python script.
Further Resources
Windows Environment Variables
FTYPE /?
Displays or modifies file types used in file extension associations
FTYPE [fileType[=[openCommandString]]]
fileType Specifies the file type to examine or change
openCommandString Specifies the open command to use when launching files
of this type.
Type FTYPE without parameters to display the current file types that
have open command strings defined. FTYPE is invoked with just a file
type, it displays the current open command string for that file type.
Specify nothing for the open command string and the FTYPE command will
delete the open command string for the file type. Within an open
command string %0 or %1 are substituted with the file name being
launched through the assocation. %* gets all the parameters and %2
gets the 1st parameter, %3 the second, etc. %~n gets all the remaining
parameters starting with the nth parameter, where n may be between 2 and 9,
inclusive. For example:
ASSOC .pl=PerlScript
FTYPE PerlScript=perl.exe %1 %*
would allow you to invoke a Perl script as follows:
script.pl 1 2 3
If you want to eliminate the need to type the extensions, then do the
following:
set PATHEXT=.pl;%PATHEXT%
and the script could be invoked as follows:
script 1 2 3
ASSOC /?
Displays or modifies file extension associations
ASSOC [.ext[=[fileType]]]
.ext Specifies the file extension to associate the file type with
fileType Specifies the file type to associate with the file extension
Type ASSOC without parameters to display the current file associations.
If ASSOC is invoked with just a file extension, it displays the current
file association for that file extension. Specify nothing for the file
type and the command will delete the association for the file extension.

Running a Python script with and without "python" [duplicate]

I have a simple script blah.py (using Python 2):
import sys
print sys.argv[1]
If I execute my script by:
python c:/..../blah.py argument
It prints argument but if I execute script by:
blah.py argument
error occurs:
IndexError...
So arguments do not pass to script.
python.exe in PATH. Folder with blah.py also in PATH.
python.exe is default program to execute *.py files.
What is the problem?
When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:
C:\>assoc .py
.py=Python.File
Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:
C:\>ftype Python.File
Python.File="c:\python26\python.exe" "%1" %*
So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:
"c:\python26\python.exe" "blah.py" foo
If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.
(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)
Brought In From Comments:
Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the
HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command
key to:
"C:\Python26\python26.exe" "%1" %*
Likely, previously, %* was missing. Similarly, set
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command The registry path may vary, use python26.exe or python.exe or whichever is already in the registry.
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
you should make the default application to handle python files be python.exe.
right click a *.py file, select "Open With" dialog. In there select "python.exe" and check "always use this program for this file type" (something like that).
then your python files will always be run using python.exe
Additionally, if you want to be able to run your python scripts without typing the .py (or .pyw) on the end of the file name, you need to add .PY (or .PY;.PYW) to the list of extensions in the PATHEXT environment variable.
In Windows 7:
right-click on Computer
left-click Properties
left-click Advanced system settings
left-click the Advanced tab
left-click Environment Variables...
under "system variables" scroll down until you see PATHEXT
left-click on PATHEXT to highlight it
left-click Edit...
Edit "Variable value" so that it contains ;.PY (the End key will skip to the end)
left-click OK
left-click OK
left-click OK
Note #1: command-prompt windows won't see the change w/o being closed and reopened.
Note #2: the difference between the .py and .pyw extensions is that the former opens a command prompt when run, and the latter doesn't.
On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the "before" and "after" values of PATHEXT were:
before: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
after .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
Here are some instructive commands:
C:\>echo %pathext%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
C:\>assoc .py
.py=Python.File
C:\>ftype Python.File
Python.File="C:\Python32\python.exe" "%1" %*
C:\>assoc .pyw
.pyw=Python.NoConFile
C:\>ftype Python.NoConFile
Python.NoConFile="C:\Python32\pythonw.exe" "%1" %*
C:\>type c:\windows\helloworld.py
print("Hello, world!") # always use a comma for direct address
C:\>helloworld
Hello, world!
C:\>
How to execute Python scripts in Windows?
You could install pylauncher. It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations:
T\:> blah.py argument
You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:
T:\> blah argument
It adds support for shebang (#! header line) to select desired Python version on Windows if you have multiple versions installed. You could use *nix-compatible syntax #! /usr/bin/env python.
You can specify version explicitly e.g., to run using the latest installed Python 3 version:
T:\> py -3 blah.py argument
It should also fix your sys.argv issue as a side-effect.
I encountered the same problem but in the context of needing to package my code for Windows users (coming from Linux).
My package contains a number of scripts with command line options.
I need these scripts to get installed in the appropriate location on Windows users' machines so that they can invoke them from the command line.
As the package is supposedly user-friendly, asking my users to change their registry to run these scripts would be impossible.
I came across a solution that the folks at Continuum use for Python scripts that come with their Anaconda package -- check out your Anaconda/Scripts directory for examples.
For a Python script test, create two files: a test.bat and a test-script.py.
test.bat looks as follows (the .bat files in Anaconda\Scripts call python.exe with a relative path which I adapted for my purposes):
#echo off
set PYFILE=%~f0
set PYFILE=%PYFILE:~0,-4%-script.py
"python.exe" "%PYFILE%" %*
test-script.py is your actual Python script:
import sys
print sys.argv
If you leave these two files in your local directory you can invoke your Python script through the .bat file by doing
test.bat hello world
['C:\\...\\test-scripy.py', 'hello', 'world']
If you copy both files to a location that is on your PATH (such as Anaconda\Scripts) then you can even invoke your script by leaving out the .bat suffix
test hello world
['C:\\...Anaconda\\Scripts\\test-scripy.py', 'hello', 'world']
Disclaimer: I have no idea what's going on and how this works and so would appreciate any explanation.
On Windows,
To run a python module without typing "python",
--> Right click any python(*.py) file
--> Set the open with property to "python.exe"
--> Check the "always use this program for this file type"
--> Append the path of python.exe to variable environment e.g. append
C:\Python27 to PATH environment variable.
To Run a python module without typing ".py" extension
--> Edit PATHEXT system variable and append ".PY" extension to the list.
Can you execute python.exe from any map?
If you do not, chek if you have proper values for python.exe in PATH enviroment
Are you in same directory than blah.py. Check this by issuing command -> edit blah.py and check if you can open this file
EDIT:
In that case you can not. (python arg means that you call python.exe whit some parameters which python assume that is filename of script you want to run)
You can create bat file whit lines in your path map and run .bat file
Example:
In one of Path maps create blah.py.bat
Edit file and put line
python C:\Somedir\blah.py
You can now run blah.py from anywere, becuase you do not need to put .bat extention when running bat files
Found an incredibly useful answer here: How to run different python versions in cmd?
I would suggest using the Python Launcher for Windows utility that introduced was into Python 3.3 a while ago. You can also manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.
Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py, .pyw, .pyc, and .pyo files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX comments at the beginning of your Python scripts.
As J.F. Sebastian suggests, Python Launcher for Windows is the best and default choice for launching different version of Python in Windows. It used to be a third-party tool, but now it is officially supported since Python 3.3.
New in version 3.3.
The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.
This is a great tool just use it!
Simply run the command:
C:>python .\file_name.py
Assuming the file name is within same folder and Python has already been added to environment variables.

When using Python Windows Launcher, is there any way to prevent having to type full path?

In Windows 8, I often use the Python Windows Launcher like
py C:/long/long/long/long/long/path/to/prog.py ...
Is there any way to set some environment setting, such as PATH or PYTHONPATH etc, to prevent having to type the full path to prog.py?
From my basic knowledge/research, PATH only helps with the py part of the command line and PYTHONPATH only helps with imports within prog.py, so how do I deal with the path to prog.py itself??
Notes:
I cannot modify the code, not even the "shebang" line, since it is needed to work on other platforms.
I cannot cd to the directory containing the programs to run them, because the programs will do something based on the directory they're run in (they'll modify the files in the directory they're run in).
I know that if I associate .py extension with the Python Windows Launcher, then I can run prog.py as the first item in the command line, and thus use PATH, but currently my .py extension is associated with my favorite editor and I'd like to keep it that way if possible (so I can double-click any Python file in Windows Explorer and edit it).
However, if someone suggests a solution where I can have a different association for Windows Explorer versus the command line, then that could be a potential solution! (i.e. in Windows Explorer, .py opens with the editor, while on command line, .py runs with Python Windows Launcher)
Add your long path to PYTHONPATH, then invoke your program as such:
python -m prog
Python will search for a module called prog and then run it as the main module.
Answer to my own question: Actually, I'm so silly. I could just set a variable for each program path (there are only a few programs paths), i.e.. prog=C:/long/path/to/prog.py and then do py %prog% .... I guess I figured out an answer to my own question that was acceptable to me.
Update: I just found something even better. I can do
doskey prog=py C:/long/path/to/prog.py $*
and then simply prog ... afterward
Now I just have to do some crazy stuff to get the doskey command into a file that will be run every time I start a console, as described here: https://stackoverflow.com/a/21040825/5182136

How to execute Python scripts in Windows?

I have a simple script blah.py (using Python 2):
import sys
print sys.argv[1]
If I execute my script by:
python c:/..../blah.py argument
It prints argument but if I execute script by:
blah.py argument
error occurs:
IndexError...
So arguments do not pass to script.
python.exe in PATH. Folder with blah.py also in PATH.
python.exe is default program to execute *.py files.
What is the problem?
When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:
C:\>assoc .py
.py=Python.File
Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:
C:\>ftype Python.File
Python.File="c:\python26\python.exe" "%1" %*
So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:
"c:\python26\python.exe" "blah.py" foo
If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.
(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)
Brought In From Comments:
Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the
HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command
key to:
"C:\Python26\python26.exe" "%1" %*
Likely, previously, %* was missing. Similarly, set
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command The registry path may vary, use python26.exe or python.exe or whichever is already in the registry.
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
you should make the default application to handle python files be python.exe.
right click a *.py file, select "Open With" dialog. In there select "python.exe" and check "always use this program for this file type" (something like that).
then your python files will always be run using python.exe
Additionally, if you want to be able to run your python scripts without typing the .py (or .pyw) on the end of the file name, you need to add .PY (or .PY;.PYW) to the list of extensions in the PATHEXT environment variable.
In Windows 7:
right-click on Computer
left-click Properties
left-click Advanced system settings
left-click the Advanced tab
left-click Environment Variables...
under "system variables" scroll down until you see PATHEXT
left-click on PATHEXT to highlight it
left-click Edit...
Edit "Variable value" so that it contains ;.PY (the End key will skip to the end)
left-click OK
left-click OK
left-click OK
Note #1: command-prompt windows won't see the change w/o being closed and reopened.
Note #2: the difference between the .py and .pyw extensions is that the former opens a command prompt when run, and the latter doesn't.
On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the "before" and "after" values of PATHEXT were:
before: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
after .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
Here are some instructive commands:
C:\>echo %pathext%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
C:\>assoc .py
.py=Python.File
C:\>ftype Python.File
Python.File="C:\Python32\python.exe" "%1" %*
C:\>assoc .pyw
.pyw=Python.NoConFile
C:\>ftype Python.NoConFile
Python.NoConFile="C:\Python32\pythonw.exe" "%1" %*
C:\>type c:\windows\helloworld.py
print("Hello, world!") # always use a comma for direct address
C:\>helloworld
Hello, world!
C:\>
How to execute Python scripts in Windows?
You could install pylauncher. It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations:
T\:> blah.py argument
You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:
T:\> blah argument
It adds support for shebang (#! header line) to select desired Python version on Windows if you have multiple versions installed. You could use *nix-compatible syntax #! /usr/bin/env python.
You can specify version explicitly e.g., to run using the latest installed Python 3 version:
T:\> py -3 blah.py argument
It should also fix your sys.argv issue as a side-effect.
I encountered the same problem but in the context of needing to package my code for Windows users (coming from Linux).
My package contains a number of scripts with command line options.
I need these scripts to get installed in the appropriate location on Windows users' machines so that they can invoke them from the command line.
As the package is supposedly user-friendly, asking my users to change their registry to run these scripts would be impossible.
I came across a solution that the folks at Continuum use for Python scripts that come with their Anaconda package -- check out your Anaconda/Scripts directory for examples.
For a Python script test, create two files: a test.bat and a test-script.py.
test.bat looks as follows (the .bat files in Anaconda\Scripts call python.exe with a relative path which I adapted for my purposes):
#echo off
set PYFILE=%~f0
set PYFILE=%PYFILE:~0,-4%-script.py
"python.exe" "%PYFILE%" %*
test-script.py is your actual Python script:
import sys
print sys.argv
If you leave these two files in your local directory you can invoke your Python script through the .bat file by doing
test.bat hello world
['C:\\...\\test-scripy.py', 'hello', 'world']
If you copy both files to a location that is on your PATH (such as Anaconda\Scripts) then you can even invoke your script by leaving out the .bat suffix
test hello world
['C:\\...Anaconda\\Scripts\\test-scripy.py', 'hello', 'world']
Disclaimer: I have no idea what's going on and how this works and so would appreciate any explanation.
On Windows,
To run a python module without typing "python",
--> Right click any python(*.py) file
--> Set the open with property to "python.exe"
--> Check the "always use this program for this file type"
--> Append the path of python.exe to variable environment e.g. append
C:\Python27 to PATH environment variable.
To Run a python module without typing ".py" extension
--> Edit PATHEXT system variable and append ".PY" extension to the list.
Can you execute python.exe from any map?
If you do not, chek if you have proper values for python.exe in PATH enviroment
Are you in same directory than blah.py. Check this by issuing command -> edit blah.py and check if you can open this file
EDIT:
In that case you can not. (python arg means that you call python.exe whit some parameters which python assume that is filename of script you want to run)
You can create bat file whit lines in your path map and run .bat file
Example:
In one of Path maps create blah.py.bat
Edit file and put line
python C:\Somedir\blah.py
You can now run blah.py from anywere, becuase you do not need to put .bat extention when running bat files
Found an incredibly useful answer here: How to run different python versions in cmd?
I would suggest using the Python Launcher for Windows utility that introduced was into Python 3.3 a while ago. You can also manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.
Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py, .pyw, .pyc, and .pyo files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX comments at the beginning of your Python scripts.
As J.F. Sebastian suggests, Python Launcher for Windows is the best and default choice for launching different version of Python in Windows. It used to be a third-party tool, but now it is officially supported since Python 3.3.
New in version 3.3.
The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.
This is a great tool just use it!
Simply run the command:
C:>python .\file_name.py
Assuming the file name is within same folder and Python has already been added to environment variables.

Categories