Python subprocess permissionerror

508 Views Asked by At

When I try to execute a file which is located inside the Program Files directory, I get a PermissionError execption.

excat error

Traceback (most recent call last):
  File "Build.py", line 24, in <module>
    subprocess.Popen([buildCMD], stdin=subprocess.PIPE)
  File "subprocess.py", line 854, in __init__
  File "subprocess.py", line 1307, in _execute_child
PermissionError: [WinError 5] Zugriff verweigert
[23948] Failed to execute script 'Build' due to unhandled exception!

Code:

import subprocess
buildCMD = '"C:/Program Files/Microchip/xc8/v2.32/bin/xc8-cc.exe" -mcpu=16f1787 -Wl,-Map=.build/main.build.map  -DXPRJ_default=default  -Wl,--defsym=__MPLAB_BUILD=1   -mdfp=C:/Program Files/Microchip/MPLABX/v5.50/packs/Microchip/PIC12-16F1xxx_DFP/1.2.63/xc8  -fno-short-double -fno-short-float -fasmfile -maddrqual=ignore -xassembler-with-cpp -mwarn=-3 -Wa,-a -msummary=-psect,-class,+mem,-hex,-file  -ginhx32 -Wl,--data-init -mno-keep-startup -mno-osccal -mno-resetbits -mno-save-resetbits -mno-download -mno-stackcall -std=c99 -gdwarf-3 -mstack=compiled:auto:auto -Wl,--memorysummary,.build/memoryfile.xml -o .build/main.build.hex main.c'

subprocess.Popen([buildCMD], stdin=subprocess.PIPE)
1

There are 1 best solutions below

1
On

Passing a string as a list is doubly wrong, though Windows is somewhat more forgiving than real computers here. You want either

subprocess.run([
    "C:/Program Files/Microchip/xc8/v2.32/bin/xc8-cc.exe",
    "-mcpu=16f1787", "-Wl,-Map=.build/main.build.map",
    "-DXPRJ_default=default", "-Wl,--defsym=__MPLAB_BUILD=1",
    "-mdfp=C:/Program Files/Microchip/MPLABX/v5.50/packs/Microchip/PIC12-16F1xxx_DFP/1.2.63/xc8",
    "-fno-short-double", "-fno-short-float", "-fasmfile",
    "-maddrqual=ignore", "-xassembler-with-cpp", "-mwarn=-3",
    "-Wa,-a", "-msummary=-psect,-class,+mem,-hex,-file",
    "-ginhx32", "-Wl,--data-init", "-mno-keep-startup",
    "-mno-osccal", "-mno-resetbits", "-mno-save-resetbits",
    "-mno-download", "-mno-stackcall", "-std=c99", "-gdwarf-3",
    "-mstack=compiled:auto:auto",
    "-Wl,--memorysummary,.build/memoryfile.xml",
    "-o", ".build/main.build.hex", "main.c"],
    stdin=subprocess.PIPE,
    check=True)

or the same as a string (but then with correct quoting around the arguments with spaces in them, notably -mdfp=C:/Program Files/...) and with shell=True (which however you usually want to avoid.)

Notice also the addition of check=True to have Python raise an exception if the subprocess fails, and the preference for subprocess.run() over subprocess.Popen unless you specifically require the subprocess to run alongside with your Python script, and then commit to managing the process object until it is terminated.