繁体   English   中英

在Windows中使用子过程将输出Shell输出到txt文件

[英]Shell output to a txt file using subprocess in Windows

我正在尝试通过使用Python 3.6中的子进程来制作输出txtfile,但问题是该文档并未真正向我展示如何在Windows中进行编码。 例如,

import subprocess     
subprocess.run(["ls", "-l"])
FileNotFoundError: [WinError 2] The system cannot find the file specified

无法以某种方式在我的计算机上工作,也没有其他示例。 您能否给我一些提示以完成此代码?

 f = open('output.txt', 'w')
 subprocess.check_output( ? , shell=True, ? )

 print("Example")
 print("Example")

 f.close()

编辑:确保您使用subprocess.runsubprocess.Popen

除了Windows的差异(如martineau在您的OP的注释中所述, ls在Windows上将无法使用,您需要使用dir命令),您想要使用subprocess.PIPE能够将命令的输出存储到变量。 然后,您应该能够遍历该变量,将其存储在文件中,如下所示:

# Save the output of the `dir` command
var = subprocess.run( <dir_command>, stdout=subprocess.PIPE, shell=True)

# Iterate through the lines saved in `var`, and write them to `file`, line by line
with open('path/to/file', 'a') as file:
    for line in var:
         file.write(line)

file.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM