操作系统不将结果写入输出fi

2024-10-01 09:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写这段代码:

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

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

注意:我尝试过同样的子进程,但总是出现错误[2]:找不到文件 我使用的是Windows7,python2.7

感谢任何帮助。在


Tags: 文件代码importtxtcmd进程os错误
3条回答

试试这个

 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"

您应该能够按照自己的方式进行此更改,因为start /wait cmd /c不需要通过os.system执行命令:

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

然而,如果你打算把它移到非windows平台上,这就不是可移植的代码。在

如果你想用更便携的方式来做,我建议你读这篇question/answer

^{pr2}$

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

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

或者,因为您似乎想要所有的子目录,请将os.walk()与{}结合使用,如glob文档中所述。无论如何,你不应该为此付出代价。在

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

相关问题 更多 >