英文:
Python Popen writing command prompt output to logfile
问题
首先,我正在在Windows上运行这个Python脚本。
我尝试每次打开一个新的命令提示符窗口,并执行一个带有一些参数的.exe文件。执行完毕后,我希望将命令提示符的输出复制到一个日志文件中。我在位置上创建了一个名为"log.log"的日志文件。当我运行脚本时,似乎根本没有将内容写入日志文件。
coreServerFullPath的路径类似于C:\Users\nanduk\Desktop\SourceCode\Core\CoreServer\Server\CoreServer\bin\Debug
。
在这个位置,我创建了一个空白文本文档并命名为log.log。
def OpenCoreServer():
os.chdir(coreServerFullPath)
# logging.basicConfig(filename="log.log", level=logging.INFO)
logging.info('你的文本在这里') # 我在日志中看到这一行。
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())
注意:代码中的双引号和角括号已被恢复为正常字符。
英文:
Firstly I am running this Python script on Windows.
I am trying to open a new command prompt window every time and want to execute a .exe with some arguments. After I execute, I want to copy the command prompt output to a log file. I created a log file at the location say "log.log". When I run the script, it doesn't seem to write the contents to the log file at all.
The coreServerFullPath is like C:\Users\nanduk\Desktop\SourceCode\Core\CoreServer\Server\CoreServer\bin\Debug
And here in this location I created a blank text document and named it to 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())
答案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:
# 在进程运行时执行一些操作
time.sleep(1)
print("CoreServer 以代码", proc.returncode, "退出")
英文:
You might be able to get away with something like
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论