【问题标题】:How to write powershell output to file? [Python]如何将powershell输出写入文件? [Python]
【发布时间】: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.exebash)。或者你应该使用模块 subprocess 中的其他函数 - 比如 subprocess.run()subprocess.check_output() 因为使用 os.system() 你无法捕获输出。
  • @furas 好的,我会试试看!

标签: python powershell


【解决方案1】:

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

试试

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

现在这不会返回 TimeSpan object,而是返回多行 string,用于在屏幕上显示对象的属性。

【讨论】:

  • 在 python 中,我收到一条错误消息:“格式列表”不被识别为内部或外部命令、可运行程序或批处理文件。 255 Out-String 也是如此,虽然它可以在普通 Powershell 中工作,但在 python 之外
  • @NoteSalad 我现在已经转义了管道字符。你能再试一次吗?
  • 对不起,我对 python 不是很熟悉,所以我不知道你是否需要转义管道字符(显然不是..)。也许您需要做更多的引用,或者正如@furas 建议的那样,从 python 运行 powershell 命令的完全不同的方式。
  • 是的,好像是这样,谢谢你的帮助!
【解决方案2】:

我无法使用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())

您甚至可以使用stdout=run() 直接重定向到文件

 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 中的文本

【讨论】:

    猜你喜欢
    • 2016-03-18
    • 2014-02-05
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多