Python Popen 将命令提示符输出写入日志文件

问题描述 投票:0回答:1

首先我在 Windows 上运行这个 python 脚本。

我每次都试图打开一个新的命令提示符窗口,并希望执行带有一些参数的 .exe。执行后,我想将命令提示符输出复制到日志文件中。我在“log.log”位置创建了一个日志文件。当我运行脚本时,它似乎根本没有将内容写入日志文件。请帮助。

coreServerFullPath 就像 C:\Users anduk\Desktop\SourceCode\Core\CoreServer\Server\CoreServer in\Debug

在这个位置我创建了一个空白文本文档并将其命名为 log.log

def OpenCoreServer():
    os.chdir(coreServerFullPath)
    #logging.basicConfig(filename="log.log", level=logging.INFO)
    logging.info('your text goes here') #I see this line in the log.
    result = subprocess.Popen('start cmd /k "CoreServer.exe -c -s" >> log.log 2>&1', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
    time.sleep(4)
    print("ABCD")
    with open('log.log', 'r') as logg:
        print(logg.read())
python logging popen
1个回答
0
投票

你也许可以摆脱类似的东西

import subprocess
import time

os.chdir(coreServerFullPath)
with open("log.log", "ab") as log:
    proc = subprocess.Popen("CoreServer.exe", stdout=log, stderr=log)
    while proc.poll() is None:
        # Do something while the process is running
        time.sleep(1)
    print("CoreServer exited with code", proc.returncode)
© www.soinside.com 2019 - 2024. All rights reserved.