0

I have encountered a bit of a conundrum while working on an automation project.

When I try to run:

program = subprocess.run("mode")

I get:

FileNotFoundError: [WinError 2] The system cannot find the file specified

However, when I replace mode with ipconfig:

program = subprocess.run("ipconfig")

it runs perfectly fine.

Anyone got an explanation? I am currently using a batch file to run the mode command, but I would like to change the arguments without editing a batch file.

Edit 1:

I also just tried using os.system:

os.system("mode")

and that also worked.

Edit 2:

Now I would just like answer to the original problem just to understand what was going on.

FlyingLightning
  • 169
  • 1
  • 7

1 Answers1

1

In Actual meaning of 'shell=True' in subprocess it pretty much says that shell=True is something that you should shy away from.

FileNotFoundError: [WinError 2] The system cannot find the file specified

Is what tipped me off that you might want shell=True in your subprocess call. If the file can't be found that means one of two things:

  1. It's not on your path.
  2. It's not actually a file.

For instance, in Linux:

$ which echo
echo: shell built-in command

That makes it pretty obvious that there is no echo file. It's just a command that's built into the shell. This may be the same thing when it comes to mode on Windows. Though this site seems to suggest that it's a MODE.COM file. You may try invoking that, as in

subprocess.run('MODE.COM')

That may work - at least according to one of the answers that I linked to

Invoking via the shell does allow you to expand environment variables and file globs according to the shell's usual mechanism. On POSIX systems, the shell expands file globs to a list of files. On Windows, a file glob (e.g., ".") is not expanded by the shell, anyway (but environment variables on a command line are expanded by cmd.exe).

So in your case, perhaps mode isn't a file, but MODE.COM is, and since Windows has a spotty relationship with casing, it seems possible that by passing shell=True, the Windows shell happily takes mode and converts it to MODE.COM for you, but without it, it tries to execute the file literally named mode, which doesn't exist.

Community
  • 1
  • 1
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290