【问题标题】:How to write the results of a batch file called in a Python script to a file如何将 Python 脚本中调用的批处理文件的结果写入文件
【发布时间】:2013-09-03 21:02:48
【问题描述】:

我有一个 Python 脚本,其中有一个 .bat 文件目录。我遍历它们并通过命令行运行每一个,然后将批处理脚本的 result 保存到文件中。到目前为止,我有这个:

import subprocess

for _, _, files in os.walk(directory):
    for f in files:
        fullpath = directory + os.path.basename(f)
        params = [fullpath]
        result = subprocess.list2cmdline(params)

但是,当我需要运行 in .bat 文件中的代码的结果时,这会将 result 变量设置为 .bat 文件的路径。有人有什么建议吗?

【问题讨论】:

    标签: python batch-file subprocess


    【解决方案1】:

    你为什么打电话给list2cmdline?这实际上并没有调用子进程。

    改用subprocess.check_output

    import os
    
    output = []
    
    for _, _, files in os.walk(directory):
        for f in files:
            fullpath = os.path.join(directory, os.path.basename(f))
            output.append(subprocess.check_output([fullpath]))
    
    print '\n'.join(output)
    

    【讨论】:

    • 感谢您的回复,快速跟进,如果我只需要在文件被访问后立即从文件中获取数据并且我需要 just 来自该文件的数据,在循环内声明输出是否更有意义?
    • @thnkwthprtls 当然,只需使用output = subprocess.check_output([fullpath]),然后使用output 进行操作。
    【解决方案2】:

    要将命令的结果(输出)写入文件,可以使用stdout 参数:

    import os
    from glob import glob
    from subprocess import check_call
    
    for path in glob(os.path.join(directory, "*.bat")):
        name, _ = os.path.splitext(path)
        with open(name + ".result", "wb") as outfile:
            check_call(path, stdout=outfile)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多