【发布时间】:2021-07-08 02:14:02
【问题描述】:
我遇到了这个问题,我可以使用 print() 函数打印出 powershell 代码输出,但是当我尝试做同样的事情时,除了这次我将输出写入文件,唯一写的东西在文件中是“0”,为什么打印输出与我编写相同的确切代码时不同,除了我这次将它“打印”到文本文件。
我希望文本文件准确包含打印功能打印到终端的内容,为什么它不工作,我怎样才能让它工作? 下面是一些图片和代码:
import os
import time
def monitorprocess(process):
run = True
time_q = float(input("How many minutes before each check? "))
while run:
timespan = os.system(f'powershell New-TimeSpan -Start(Get-process {process}).StartTime')
try:
open(f'powershellpython\{process}.txt','x')
except:
pass
with open(f'powershellpython\{process}.txt',"w") as file:
file.write(str(timespan))
print(timespan)
time.sleep(time_q*60)
def processes():
process = input("What is the name of your process, if you are unsure, type 'get-process', and if you want to use ID (this works with multiple processes with the same name) type ID: \n")
if process == "get-process":
print(os.system("powershell get-process"))
process = input("What is the name of your process, if you are unsure, type 'get-process', and find your process: \n")
else:
monitorprocess(process)
processes()
打印还有一些输出,即“小时”和“天”,但这在这种情况下并不重要。
【问题讨论】:
-
也许你应该做
python script.py > output.txt- 并且它可能应该将控制台输出重定向到文件(至少它适用于Linux上的cmd.exe或bash)。或者你应该使用模块subprocess中的其他函数 - 比如subprocess.run()或 subprocess.check_output() 因为使用os.system()你无法捕获输出。 -
@furas 好的,我会试试看!
标签: python powershell