This question already has an answer here:
Python Script does not take sys.argv in Windows
(1 answer)
Closed 7 months ago.
I have got a Python Script called "gcc_opt.pyw" and I included its directory to the Windows PATH environment variable.
But not a single commandline argument is passed to the script. Printing out sys.argv tells me there is only the filename in the argv-list.
This command:
gcc_opt HelloWorld.c -o HelloWorld.exe -shared
results in
["C:\\Scripts\\gcc_opt.pyw"]
Can you tell me why there are no other arguments ?
I don't know if it is important, but I've set python.exe to be the default program to execute .pyw files as i don't see any prints using pythonw.exe (why ever this is).
The reason why you're not getting parameters is because you broke the .py
association so you could double-click those files to open them in NotePad++,
and subsequently broke the .pyw association to do what .py is supposed to do.
In short, you forgot to include the %* at the end of your Python.exe command
line for your "customized" (mangled) .pyw association.
The ASSOC and FTYPE commands are used to show associations and file types, ie,
what program gets run to handle a file with a particular extension. Here is
what those commands produce on my system:
C:\test>assoc .py
.py=Python.File
C:\test>assoc .pyw
.pyw=Python.NoConFile
C:\test>ftype python.file
python.file="C:\Python27\python.exe" "%1" %*
C:\test>ftype python.noconfile
python.noconfile="C:\Python27\pythonw.exe" "%1" %*
The normal .py association runs python.exe with a console window so that you
can see the output of print statements.
The normal .pyw association runs pythonw.exe with no console window.
You can see at the end of each command line, there is a %*. This is what sends
the parameters to a command. (Actually, %1 is the first parameter, and %*
means "all remaining parameters".)
When you try to run a python file at the command line without typing its
extension or the initial "python" command, a few things happen.
First the PATHEXT environment variable is used to find a matching extension.
In your case it finds that your command name "gcc_opt" + .PYW results in a
matching file.
Then the association for .PYW files is looked up, which finds the filetype
Python.NoConFile, which in your case is set to "python.exe" (supposed to be
pythonw.exe). (You can see these in the registry under HKEY_CLASSES_ROOT.)
The system then creates an actual command line from the command template found
for that filetype, which in your case is probably
"[your-python-path]python.exe" "%1"
This tells it to use just the first parameter, your python script name
"gcc_opt.pyw".
The quick fix is to add the %* to the end of that command.
The CORRECT fix would be to put things back to the correct associations and
open Python files for editing by a more standard method (drop icon onto
NotePad++, or maybe right click and Edit with NotePad++).
You should rename it to .py.
.pyw is intended to be used for GUI applications, because they don't need console window.
Related
With Linux, if you create a file mycommand with +x permission in a folder which is in the PATH, containing a Python shebang #!..., then calling mycommand from command line works, no matter the current directory.
How to have the equivalent on Windows? i.e. I have a folder D:\myscripts\ which is in the PATH, containing a few personal scripts like mycommand.py.
How to make that calling mycommand or maybe just python mycommand from commandline will work, no matter the current working directory?
TL;DR: I'd like to avoid to have to do
python D:\myscripts\command.py
each time I want to call every-day-use personal scripts from D:\myscripts\
Note: .py files are associated with my text editor (i.e. when double-clicking on a .py file, it is opened with the text editor) and I want to keep this.
Solution 1
I finally did like this:
put D:\myscripts\ in the PATH (with setx, see How to update system PATH variable permanently from cmd?)
create a batch file: D:\myscripts\mycommand.bat containing:
#python d:\myscripts\mycommand.py
That's it!
Solution 2
Here is a solution from various comments from #ErykSun:
Open the system environment variables editor and ensure that "D:\myscripts" is in PATH (do not use quotes) and ".PY" is in PATHEXT (do not use quotes).
Create a test file D:\myscripts\test_command.py with the line import sys; print(sys.executable); print(sys.argv).
In a new command prompt that was opened from Explorer (to get the updated environment variables), run the test script from another directory as test_command spam eggs. If it runs with the expected Python installation and the command-line arguments "spam" and "eggs" are correctly passed, then you're done.
When double-clicking and running at the command prompt, the shell executes the default action for the filetype. If the filetype doesn't explicitly define a default action, the shell uses the "open" action, and if that's not defined it uses the filetype's first defined action, whatever that is. Python configures an "open" action for its "Python.File" filetype and additional context-menu (right-click) actions for editing with IDLE.
There are other directions you can go with this. You can use shell links. Add ".LNK" to PATHEXT and remove ".PY". Then for each script that you want to run, create a shell link (.LNK shortcut file) in D:\myscripts that runs the script explicitly as "path\to\python.exe" "\path\to\script". Leave the working directory field empty, so that it inherits the working directory of the parent process. For example, create D:\myscripts\test_command.lnk to run D:\myscripts\test_command.py.
In this case, you would run the script as test_command, which will find and execute "test_command.lnk". To get the default Sublime edit action, you would explicitly run test_command.py with the ".PY" extension.
Solution 3
Create an .exe file in c:\python37\scripts\ with this method: How to create a .exe similar to pip.exe, jupyter.exe, etc. from C:\Python37\Scripts?
but it's more complicated since it requires a package, etc.
How to associate .py files to open CMD with py then the filename? Maybe in a .bat file?
sorry about my poor English, and if I insist on subjects you already master, it's my first constructive answer here ;p
I'm not sure about what you want to achieve but from your question and its tags I assume tha you want to :
run ".py" file containing a python script from the file explorer by double clicking it
have a cmd.exe window open after this action with your python script interpreted
have a way to review this scipt output without relying on superman eyes able to gasp 65536 characters per millisecond
So basically, if you have a script printing "Hello World !", you want to click on it, and see in a cmd.exe window the text "Hello World !" displayed to validate that your script is working properly ? To make it short you are RIGHT, a .bat file will be enough to do the trick, even if there is a whole bunch of alternatives including executable generation to embed a full python interpreter (see http://www.py2exe.org/), or simply adding a wait loop at the end of your script, but having a batch script associated is probably the lightest and easiest solution in your case.
As you figured out, associating .py files with the python interpreter will run your scripts but the console window will dissapear immediatly on completion without letting you the time to consider the output. You just need to associate .py files (right click -> open with, if you want to do it programatically it's possible to set this in the windows registry) with a .bat script that will do the job, that is, run the script and wait until you are ready to "leave".
This batch script will take the python script you clicked on as an argument, run it with your python interpreter and pause it's execution, waiting for your input before leaving. Since the default windows file association will execute your target program and pass it the file executed (should it be a click or a "start XXX" command) it's pretty straightforward, the bricks to do this in batch are :
program_name argument : to directly call an external command, so "python my_script.py" will run the python.exe program (no need to add the ".exe" or "'.com" part since it's an obvious case for windows) with my_script.py as argument, provided that your python executable directory is in your PATH environment variable, otherwise you will have to provide the full path, ie: "C:\Python27\python.exe my_script.py" .
%X : to reference command line arguments sent to your script (%1 for the first one, then %2 etc.,)
pause : a command that will display the message "Press any key to continue ...", and obviously wait for any key before leaving your script
evantually, #echo off : to avoid printing each batch command before its execution
So, assuming that your python interpreter is installed in C:\Python27 (please replace with whatever version / location for your python.exe, or just "python" if it's in your PATH) your batch script could look like something like this :
#echo off
C:\Python27\python.exe %1
pause
Save it somewhere, associate it with .py files, and you are done. HTH
You can do it in two separate ways:
First, you can rename your .py file to .pyw and just open it and the script would be executed immediately (with pythonw.exe) but this is not showing you a console output.
Or you can simple associate your .py files with standard python.exe which will show the console output.
I have written a python script (lets call it myTest.py) and would like to launch it from the windows command promt.
My python interpreter was added to the PATH environment variable, therefore i can launch it just fine as python myTest.py and it is executed successfully.
I would however like to launch it by simply typing myTest.py in the command promt. But if I do this, the file is opened in PyCharm and is not executed.
I have checked assoc .py which gives me .py=Python.File, as well as ftype Python.File which gives me Python.File="C:\WINDOWS\py.exe" "%L" %*. As far as I understand this, a .py file should be launched with py.exe at the given path.
(If you are as confused as I was by the %L option of ftype, that is not mentioned in its help document: It makes no difference in my case and is equivallent to %0 and %1. Source: https://mail.python.org/pipermail/python-list/2015-November/699263.html)
Can anyone explain why my script is opened in PyCharm and not launched with py.exe? What do I have to do to simply execute it instead?
Edit:
The answer of #Hamed169 solves the problem (thanks!), but doesnt't give any details on why there is a difference between the program that is used to open a file and the one that is returned by ftype.
For everyone that is interested in why there is a difference I have found the following question (has currently no final answer, but quite a bit of information): https://superuser.com/questions/204354/how-do-i-get-ftype-assoc-to-match-windows-explorer
Right Click on a .py file
Click Properties
Click "change" in Opens with:
Select your python interpreter instead PyCharm
Run your .py files and enjoy:)
Thanks a lot Hame
We should change it to the python.exe file path, i.e., (in my case):
C:\Users\NEDA\AppData\Local\Programs\Python\Python38-32
File associations on my machine (winxp home) are such that a python script is directly opened with the python interpreter. If I double click on a python script a console window runs and every thing is fine - as long as there is no syntax error in the script.
In that case the console window opens up for a moment but it is closed immediately. Too fast to read the error message.
Of course their would be the possibility to manually open a console window and to execute the script by typing python myscript.py but I am sure that there is a more convenient (i.e. "double click based") solution.
Make a batch file:
C:\Python26\python.exe %1
IF %ERRORLEVEL% NEQ 0 PAUSE
Use that as your file association instead of python.exe directly. This will only cause the PAUSE statement to execute if python.exe returns an error
The canonical way to run a command in a command prompt window that doesn't close is
cmd /k "your command"
The way that I do it is i right click the script that I saved from notepad to a .py file, then i click edit with IDLE, This is an editing thingy, but you can also run modules from it
I've left a comment at rossipedia's answer about a similar situation, but I doubt it's gonna get noticed in a 8 year old post. So, I've experimented myself.
I have a python script that processes a folder that's dropped on it. As I add new lines, sometimes I get syntax errors, and I can't view them because the command prompt window closes too quickly. In order to keep the window open after an error, I had to modify rossipedia's code. I needed a way to pass a path to the bat file (drop a folder on it) and make the bat pass that path to the python script. The following does that:
debug.bat:
#echo off
REM debug.bat and myscript.py should be in the same dir, otherwise use absolute path for the python script
C:\Users\%username%\AppData\Local\Programs\Python\Python36-32\python.exe "%~dp0\myscript.py" %1
IF %ERRORLEVEL% NEQ 0 PAUSE
myscript.py:
import sys
print("printing dropped file path:")
print(sys.argv[1])
input()
If I get an error, I just use the debug.bat to view the error, and it works the same (drop a folder on it).
Update:
In my actual python script, I have this line:
sys.path.append("modules")
This doesn't work when I use debug.bat. "modules" is a folder that's in the same folder with the python script. When the script is called with debug.bat, the current working directory changes to the dropped file's directory. So, to get the path to "modules", I had to use absolute path:
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "\\modules")
I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.
Is there some kind of configuration that needs to be done somewhere for this work?
Sure. From a mindless technology article called "Make Python Scripts Droppable in Windows", you can add a drop handler by adding a registry key:
Here’s a registry import file that you can use to do this. Copy the
following into a .reg file and run it
(Make sure that your .py extensions
are mapped to Python.File).
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]
#="{60254CA5-953B-11CF-8C96-00AA00B8708C}"
This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with 86C86720-42A0-1069-A2E8-08002B30309D.
A comment in that post indicates that one can enable dropping on "no console Python files (.pyw)" or "compiled Python files (.pyc)" by using the Python.NoConFile and Python.CompiledFile classes.
write a simple shell script (file.bat)
"C:\python27\python.exe" yourprogram.py %*
where %* stands for the all arguments you pass to the script.
Now drag & drop your target files on the file.bat icon.
With an installed python - at least 2.6.1 - you can just drag and drop any file on a python script.
import sys
droppedFile = sys.argv[1]
print droppedFile
sys.argv[0] is the script itself. sys.argv[n+1] are the files you have dropped.
Try using py2exe. Use py2exe to convert your python script into a windows executable. You should then be able to drag and drop input files to your script in Windows Explorer. You should also be able to create a shortcut on your desktop and drop input files onto it. And if your python script can take a file list you should be able to drag and drop multiple files on your script (or shortcut).
Create a shortcut of the file. In case you don't have python open .py files by default, go into the properties of the shortcut and edit the target of the shortcut to include the python version you're using. For example:
Target: C:\Python26\python.exe < shortcut target path>
I'm posting this because I didn't want to edit the Registry and the .bat workaround didn't work for me.
1). create shortcut of .py
2). right click -> properties
3). prefix "Target:" with "python" so it runs the .py as an argument into the python command
or
1). create a .bat
2). python some.py %*
these shortcut versions are simplest for me to do what i'm doing
otherwise i'd convert it to a .exe, but would rather just use java or c/c++
Late answer but none of the answers on this page worked for me.
I managed to enable/fix the drag and drop onto .py scripts using:
HKEY_CLASSES_ROOT\.py -> Set default value to Python.File
HKEY_CLASSES_ROOT\Python.File\Shell\Open -> Create a key called Command with default value "C:\Windows\py.exe" "%1" %*
CLASSES_ROOT\Applications\py.exe\open\command -> Create keys if the don't exist and set the default value to "C:\Windows\py.exe" "%1" %*
CLASSES_ROOT\Python.File\ShellEx -> create key DropHandler with default value {86C86720-42A0-1069-A2E8-08002B30309D}
That's it. Test it by dragging a file onto the python script:
import sys
args = sys.argv
print(args)
For those who use argv in .py script but still can't drag files to execute,
this could be solved by simply using Python Launcher (with rocket icon)
the script property "Open File" was set as python.exe,
which has no knowledge that the script needs command-line arguments "%*"
Refer to: https://bugs.python.org/issue40253