2

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

3
  • a = "Hello World" print(a) Commented Aug 20, 2020 at 16:42
  • Assign it to a var? Commented Aug 20, 2020 at 16:43
  • the code I provided is an illustration and not the actuall code. Of course this is easier but it doesn't meet the functionality I'm looking for. Commented Aug 20, 2020 at 17:26

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

not that is not the case, this is all contained in a single script.
-1

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.

1 Comment

the code I provided is an illustration and not the actuall code. Of course this is easier but it doesn't meet the functionality I'm looking for.

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.