2

I am using Python 3.10.6 and Miniconda 3

What I'm trying to do is write a python script which will open a .cmd file. simple enough, but the problem is it has to be opened in anaconda. I've been able to have my script open the .cmd through the standard command line, and I've been able to have the script open anaconda. But I'm unable to do both in sequence, open the anaconda terminal and then pass a command to it, instructing it to open the .cmd

opening anaconda:

path = 'C:\\Users\...\shortcuts\\conda.lnk'
cmds = 'C:\\Users\\...test.cmd'
cmd_result = subprocess.run(path, shell=True, check=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True,
                                text=True )
print(cmd_result.args)
print(cmd_result.stdout)

this works properly when i open either anaconda path or test.cmd directly using the subprocess.run function. but when I attempt to open test.cmd as a command argument in the anaconda terminal, it doesn't work

path = 'C:\\Users\...\shortcuts\\conda.lnk'
cmds = [path,'/C','C:\\Users\\...test.cmd']
cmd_result = subprocess.run(cmds, shell=True, check=True,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                universal_newlines=True,
                                text=True )

I believe this is the relevant part of the error code it returns

  File "C:\Users\...dream_restart_module.py", line 17, in dream_restart
    cmd_result = subprocess.run(cmds, shell=True, check=True,
  File "C:\Users\...Python310\lib\subprocess.py", line 524, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['C:\\Users\\...shortcuts\\conda.lnk', '/C', 'C:\\Users\\...test.cmd']' returned non-zero exit status 1.

I feel like I am missing something obvious here, perhaps about the syntax or limitations of subprocess. Any guidance would be appreciated

echocosm
  • 33
  • 2

1 Answers1

0

When you use subprocess.run() with shell=True, the arguments you give it as part of your cmds list are passed directly to the shell, rather than as arguments to the initial command.

So if you intend to pass '/C' and 'C:\\Users\\...test.cmd' as arguments to path, you should either not declare shell=True (preferred) or provide your cmds as a single, space-separated string (less preferred), like path+' /C C:\\Users\\...test.cmd' or ' '.join(cmds).

L0tad
  • 574
  • 3
  • 15
  • See https://stackoverflow.com/a/26417698/4450498 for a more detailed explanation of this. – L0tad Sep 07 '22 at 16:36