使用python将cmp输出定向到文件

2024-04-26 10:51:04 发布

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

我正在尝试这样的事情,但我不知道为什么它不工作。你知道吗

 for files in os.listdir("."):
    if files.endswith(".o"):
       str = "cmp "+ str1+"  "+str2 +" > s.txt "
       subprocess.Popen(str, shell=True)

如果我没有te.txt,我会得到输出,但是当我尝试将输出定向到一个文件时,不会创建该文件。有人能告诉我这里怎么了吗?你知道吗


Tags: 文件intxtforifosfiles事情
1条回答
网友
1楼 · 发布于 2024-04-26 10:51:04

试试这个

import os

for files in os.listdir("."):
    if files.endswith(".o"):
       str = "cmp "+ str1+"  "+str2 +" > s.txt "
       os.system(str)

如果使用subprocess,则需要将所有参数作为单词列表 例如:

import subprocess
subprocess.Popen(["ls", "-la"])

最后一句话,您不需要从... > file.txt输出put,您可以使用subprocess来实现。例如

subprocess.Popen(["ls", "-la"], stdout=anyfile)

相关问题 更多 >