Reputation: 33
I have a script that returns an output in the console, eg (not the actual code just an example):
print("Hello World")
I want to be able to catch this output as a string and store it as a variable:
print("Hello World")
# function to catch previous line output and store it as a variable
Upvotes: 2
Views: 785
Reputation: 408
I'm assuming by the wording in your question that you are running the first print command in a different script than the first one. In that case you can run it using the subprocess module and catch the output like this:
from subprocess import run
result = run(['script.py'], capture_output=True)
previous_output = result.stdout
Upvotes: 2
Reputation: 431
You can just do that
a = "Hello World !"
print(a)
it's easier than trying to capture it after printing the actual string, but if you insist, @Blupper already answered your question.
Upvotes: -1