子流程.运行.vs.直接在cmd中运行命令

2024-09-22 20:36:51 发布

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

运行以下脚本时,我收到一个奇怪的“拒绝访问-\”错误\警告:

import os
import subprocess

directory = r'S:\ome\directory'
subprocess.run(['find', '/i', '"error"', '*.txt', '>Errors.log'], shell=True, cwd=directory)

我还检查了:

^{pr2}$

它们都是printTrue。在

subprocess命令正在运行但进程没有终止时,将打印错误消息;不会引发任何内容。因此,即使不指定异常,将其包装成try-except也不会捕获任何内容。当该过程结束时,将创建文件(Error.log),但包含错误的结果。在

从在指定目录中打开的cmd运行完全相同的命令(find /i "fatal" *.txt >Error.log)会产生正确的结果。在

这两种方法在哪方面不同?


方法1(来自Python):

subprocess.run(['find', '/i', '"error"', '*.txt', '>Errors.log'], shell=True, cwd=r'S:\ome\directory')

方法2(来自cmd):

S:\ome\directory>find /i "error" *.txt >Errors.log

Tags: 方法runimporttxtlogtrue错误error
3条回答

尝试传递stdout参数的输出文件处理程序:

import shlex
import subprocess

with open("Errors.log", "w") as output_fh:
    # command = ['find', '/i', '"fatal"', '*.txt']
    command = shlex.split(r'find /i \"fatal\" *.txt')
    try:
        subprocess.run(command, shell=True, stdout=output_fh)
    except subprocess.CalledProcessError:
        pass

也许,这是实现任务的唯一方法,因为子流程.运行不运行由其参数描述的重定向(>;或>>;)。在

我仍然不确定到底是什么问题,只是改变了:

subprocess.run(['find', '/i', '"error"', '*.txt', '>Errors.log'], shell=True, cwd=r'S:\ome\directory')

收件人:

^{pr2}$

就这样。在

如图所示,手动缝合该命令起作用。如果有人对此事有更多的消息,我将不胜感激。在

FromPopen构造函数(由调用子流程.运行)在

On Windows, if args is a sequence, it will be converted to a string in a manner described in Converting an argument sequence to a string on Windows. This is because the underlying CreateProcess() operates on strings.

问题是CreateProcess不支持重定向。在

请参见:How do I redirect output to a file with CreateProcess?

相关问题 更多 >