Search code examples
batch-filefile-associationexecutable-path

Need to associate files with executable in batch file


I need to write a batch script to associate .py files with pythonw.exe. So I need to do two things: 1) find the path of the pythonw.exe, and then associate .py files, or specifically afile.py with pythonw.exe.

I know that I can find the path to pythonw.exe like this:

for %i in (python.exe) do @echo. %~$PATH:i

But the above command does not work from a batch file -- but rather it only works fro a command line.

I also know that I can use

assoc 

to associate file extensions with executables.

How do I put this all together into one batch file?


Solution

  • First use %% instead of % inside batch files:

    for %%i in (python.exe) do @echo. %%~$PATH:i
    

    Then, use ftype to associate a command or a executable to a file type. After that, use assoc to associate the extension .py to the file type created before with ftype.

    Your code should look like this:

    @echo off
    for %%i in (pythonw.exe) do set "pypath=%%~$PATH:i"
    ftype PythonFile="%pypath%"
    assoc .py=PythonwFile