Trying to launch subprocess from macro

159 views Asked by At

I am trying to launch a python subprocess from excel using PYXLL, but it seems to have trouble launching the cmd window and running commands.

Below is a sample of what I am trying to run:

  @xl_macro()
    def test():
        if 1 == 1:
            xlcAlert("Next line nothing happens") #Popup appears
            p = subprocess.Popen(r'start cmd /k', shell=True, creationflags=subprocess.CREATE_NEW_CONSOLE, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
            xlcAlert("{}".format(p.pid)) #p was never launched

I am trying to capture values from excel and pass them in a subprocess. This works when executing in my IDE: data is read from excel and then subprocess launches window. However, once adding the decorator to have it run as macro in EXCEL, the script will just stop once subprocess.Popen line is reached. Is there any way to launch a subprocess from pyxll?

1

There are 1 answers

0
pcp23 On

After investigation, and thanks to Charles Duffy, Microsoft Office SandBoxing kills the shell subprocess. This has been implemented for security reasons in latest versions.

The simple solution is to run subprocess with shell=False and pass the args in a list:

p1 = subprocess.Popen(cmdlist, shell=False)

The Sandboxing will not terminate the process - python window will open while script is running.