0

I am having this problem where I can print out the powershell code output with the print() function, but when I try to do the same, except this time I write the output to a file, the only thing that is written in the file is "0", why would the printed output be different from when I write the same exact code, except that I this time "print" it to a text file.

I want the text file to contain exactly what the print function prints to the terminal, why isn't it working, and how can I get it to work?? Here are some pictures and the code:

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

And there is some more output with the print, that being "hours" and "days", but that does not really matter in this context.

2
  • maybe you should do python script.py > output.txt - and probably it should redirect console output to file (at least it works in cmd.exe or bash on Linux). OR you should use other functions in module subprocess - like subprocess.run() or subprocess.check_output() because with os.system() you can't catch output. Commented Jul 7, 2021 at 17:27
  • @furas Ok, I will try that out! Commented Jul 7, 2021 at 17:33

2 Answers 2

1

I can't test it with powershell because I don't use Windows but to catch output you should use other methods in subprocess

ie. subprocess.check_output()

 import subprocess

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

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

ie. 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())

Probably you could even redirect run() directly to file using stdout=

 with open('output.txt', 'w') as file:
     subprocess.run(cmd, shell=True, stdout=file)

Using os.system() you can catch only return code (error code) and you could only do python script.py > output.txt to get text in file output.txt

Sign up to request clarification or add additional context in comments.

1 Comment

subprocess.run() worked for me, thx.
0

What you see on screen can be produced by PowerShell.

Try

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

This now will not return a TimeSpan object, but rather a multiline string meant to display the properties of the object on screen.

4 Comments

In python I get an error stating: 'Format-List' is not recognized as an internal or external command, operable program or batch file. 255 The same goes for Out-String Although it works in normal Powershell, outside of python
@NoteSalad I have escaped the pipe characters now. Can you try again please?
Sorry, I'm not really familiar with python, so I have no idea if you need to escape the pipe characters or not (apparently not..). Perhaps you need to do some more quoting or as @furas suggests, an entirely different way to run a powershell command from python.
yup, seems like it, thanks for the help htough!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.