1

I am writing this piece of code :

import os
os.system("start /wait cmd /c dir/s *.exe > Allexe1.txt")

What it is supposed to do is to get all exe files and write the result on to the file. But I get an empty file .

Note: I have tried the subprocess for the same and I always get the error Error[2] : file not found I am using Windows 7 , python2.7

Any help is appreciated .

ggorantl
  • 75
  • 1
  • 11

3 Answers3

2

You should be able to do it your way with this alteration as start /wait cmd /c isn't required to execute a command via os.system:

import os
os.system("dir/s *.exe > Allexe1.txt")

However this isn't portable code if you were going to move it to a non windows platform.

If you wish to do it in a more portable fashion I recommend you read this question/answer

import sys,os

root = "/home/patate/directory/"

for path, subdirs, files in os.walk(root):
    for name in files:
        # filter for files with an exe extension here
        print os.path.join(path, name)
Community
  • 1
  • 1
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
1

You should not enumerate files in Python this way. Instead, use the included glob module:

import glob
for filename in glob.glob('*.exe'):
    print filename

Or since you seem to want all subdirectories, use os.walk() combined with fnmatch as mentioned in the glob docs. In any case you should not shell out for this.

https://docs.python.org/2/library/glob.html

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

Try this

 import os

 result = os.popen("start /wait cmd /c dir/s *.exe > Allexe1.txt").read()
 if result is not None:
     #this is your object with all your results
     #you can write to a file
     with open('output.txt', 'w') as f:
         f.write(result)
 #you can also print the result to console.
     print result
 else:
     print "Command returned nothing"
Zuko
  • 2,764
  • 30
  • 30
  • I'm not sure about your command but make sure your command is correct – Zuko Sep 08 '14 at 04:47
  • The command would have exclude the problematic `start /wait cmd /c` and remove the redirection `> Allexe1.txt` so that there is output to capture. – Michael Petch Sep 08 '14 at 04:52