【问题标题】:os.system does not write the result to output fileos.system 不将结果写入输出文件
【发布时间】:2014-11-01 05:57:09
【问题描述】:

我正在写这段代码:

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

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

注意:我已经尝试过相同的子进程,但我总是收到错误 Error[2] : file not found 我正在使用 Windows 7,python2.7

感谢任何帮助。

【问题讨论】:

  • 你真的有没有空格的dir/s吗?
  • 是的,约翰,这是我测试时在 cmd 中工作的命令。我正在尝试将其嵌入 python os.system

标签: python python-2.7 os.system


【解决方案1】:

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

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

或者由于您似乎想要所有子目录,请使用 os.walk()fnmatch 结合使用,如 glob 文档中所述。无论如何,您不应该为此付出任何代价。

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

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      【解决方案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 并删除重定向> Allexe1.txt 以便捕获输出。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 2016-10-08
      • 2010-09-15
      • 1970-01-01
      相关资源
      最近更新 更多