0

I'm doing this simple thing

import subprocess
with cd("/home/myuserid"):
  subprocess.call("ls ")

where cd is taken from here and it just does not work (same with any other path):

OSError: [Errno 2] No such file or directory

Community
  • 1
  • 1
Bob
  • 10,741
  • 27
  • 89
  • 143

1 Answers1

2

You have an extra space after ls, which is causing your issue. Remove that and it should work fine.

import subprocess
with cd("/home/myuserid"):
    subprocess.call("ls")

When you use subprocess without shell=True, it interprets the entire string you pass as the command to execute. So it looks for a program literally called "ls " when you provide that extra space, which of course doesn't exist.

If you were to use shell=True, it would work fine even with the extra space, because a /bin/sh shell would be used to run the command, and the shell wouldn't care about the extra space. In general it's safer to use the default of shell=False, though, so I'd stick with that.

dano
  • 91,354
  • 19
  • 222
  • 219