5

I'm playing around with subprocess.Popen for shell commands as it seems it has more flexbility with regards to piping compared to subprocess.run

I'm starting off with some simple examples but I'm getting FileNotFoundError:

I was told that shell = True is not necessary if I make the arguments as proper lists. However it doesn't seem to be working.

Here are my attempts:

import subprocess
p1 =subprocess.Popen(['dir'], stdout =subprocess.PIPE)

output = p1.communicate[0]


p = subprocess.Popen([ "dir", "c:\\Users"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outputs = p.communicate()

Both are leading to FileNotFoundError

Moondra
  • 4,399
  • 9
  • 46
  • 104

3 Answers3

6

As dir is simply a command understood by cmd.exe (or powershell.exe) then you could:

subprocess.Popen(["cmd", "/c", "dir", "c:\\Users"], stdout=subprocess.PIPE)

which corresponds to doing the following in a shell

C:\>cmd /c dir c:\Users

You may find you have to fully path cmd, as c:\\Windows\\System32\\cmd.exe

donkopotamus
  • 22,114
  • 2
  • 48
  • 60
  • Thank you. I didn't know about `/c` flag. Is there a way to have the shell stay open after execution. I tried using '/k' as a flag, instead of '/c' but the shell is still closing. – Moondra Feb 28 '18 at 00:39
0

Your problem is that "dir" is an internal Windows command and your "popen" is looking for the name of an executable. You could try setting up a "dir.bat" file that runs the "dir" command to see if this works or simply try any of the commands in \Windows\system32 instead.

DevonMcC
  • 435
  • 4
  • 4
-2

Try this (on windows):

import subprocess

file_name = "test.txt"

sp = subprocess.Popen(["cmd", "/c", 'dir', '/s', '/p', file_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = sp.communicate()
output = output[1].decode()

if file_name in output:
    print("yes")
else:
    print("no")

On Linux, replace the call to subprocess like this:

sp = subprocess.Popen(['find', '-name', file_name, '/'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

I htink the key is in: stdout=subprocess.PIPE, stderr=subprocess.PIPE

Kalma
  • 111
  • 2
  • 15