如何将powershell输出写入文件? [蟒蛇]

时间:2021-07-07 11:30:49

标签: python powershell

我遇到了这个问题,我可以使用 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()

output output in text document

打印还有一些输出,即“小时”和“天”,但这在这种情况下并不重要。

2 个答案:

答案 0 :(得分:0)

您在屏幕上看到的内容可以由 PowerShell 生成。

试试

timespan = os.system(f'powershell New-TimeSpan -Start(Get-process {process}).StartTime | Format-List | Out-String')

现在不会返回 TimeSpan 对象,而是返回一个多行字符串,用于在屏幕上显示对象的属性。

答案 1 :(得分:0)

我无法用 powershell 测试它,因为我不使用 Windows 但要捕获输出,您应该使用 subprocess 中的其他方法

即。 subprocess.check_output()

 import subprocess

 output = subprocess.check_output(cmd, shell=True)

 with open('output.txt', 'w') as file:
     file.write(output.decode())

即。 subprocess.run()

 import subprocess
 from subprocess import PIPE

 output = subprocess.run(cmd, shell=True, stdout=PIPE).stdout

 with open('output.txt', 'w') as file:
     file.write(output.decode())

也许您甚至可以使用 run()

stdout= 直接重定向到文件
 with open('output.txt', 'w') as file:
     subprocess.run(cmd, shell=True, stdout=file)

使用 os.system() 只能捕获 return code (error code) 并且只能执行 python script.py > output.txt 来获取文件 output.txt 中的文本

相关问题