0

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?

pcp23
  • 11
  • 3
  • Note that a lot of security tools will flag this, so you might well see the Excel document using this get quarantined. For that matter, depending on the Excel version and appropriate configuration, it might be getting squashed by Office's own sandboxing. – Charles Duffy Jun 23 '22 at 18:18
  • That is such a bummer. It was my only solution to argparse some values to another script - as that script takes a long time to process. I am able to launch multiple instances of the script as well by using subprocess. Any suggestions? – pcp23 Jun 23 '22 at 18:51
  • If using `subprocess` works in general, then why exactly do you need `cmd` in this specific case? (I'm curious if we can get a subprocess invocation to do the thing you're looking to accomplish directly). – Charles Duffy Jun 23 '22 at 19:07
  • 'start cmd /k' was my way to forcing a new cmd window to follow along while the script is running. Without it, it would run in the background although the subprocess had shell=True and creationflags=subprocess.CREATE_NEW_CONSOLE. – pcp23 Jun 23 '22 at 20:01
  • Gotcha. Unfortunately, I'm not going to be a huge amount of help here -- I work near a bunch of Windows security folk (and so sometimes pick things up by osmosis), but I'm a Unix developer myself. Hopefully the above is enough for someone with more relevant experience to suggest a solution. – Charles Duffy Jun 24 '22 at 14:11

1 Answers1

0

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.

pcp23
  • 11
  • 3