os.system不会将结果写入输出文件

时间:2014-09-08 03:26:37

标签: python python-2.7 os.system

我正在写这段代码:

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

它应该做的是获取所有exe文件并将结果写入文件。但我得到一个空文件。

注意:我已经尝试了相同的子进程,我总是得到错误错误[2]:找不到文件 我使用的是Windows 7,python2.7

感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

由于start /wait cmd /c执行命令不需要os.system,您应该可以通过此更改方式执行此操作:

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

但是,如果您要将其移至非Windows平台,则这不是可移植代码。

如果您希望以更便携的方式进行此操作,我建议您阅读此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)

答案 1 :(得分:1)

您不应该以这种方式枚举Python中的文件。相反,请使用包含的glob模块:

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

或者,由于您似乎想要所有子目录,请使用os.walk()文档中提到的fnmatchglob。无论如何,你不应该为此付出代价。

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

答案 2 :(得分:1)

试试这个

 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"
相关问题