-1

This is a silly question, but it's giving me a lot of trouble. I'm trying to capture an output into a variable

a='jobid'
p=exec(a)
print(p)
output:None

You guys might say why not just use the variable 'a' rather than executing it, but I have a cascading function next to it. And I can't use the variable 'a'.And the value 'job ID' in the variable 'a' comes from a data frame and needs to catch value, as 'job ID' is a parameter in my code. Can anyone please help me out?

I also tried the below code:

a='jobid'
p=exec('print(jobid)')
print(p)

But it didn't worked out.

younus
  • 412
  • 2
  • 10
  • 20
  • `exec()` doesn't return anything. Hence `p=exec(a) ;print(p)` will print `None`. – Ch3steR Feb 02 '20 at 10:51
  • Not only `exec` does not return anything, `print` does not return anything as well, so I'm very confused as to what you expect `p` to be – DeepSpace Feb 02 '20 at 10:52
  • Yuo probably want to [use subprocess](https://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string) – MrBean Bremen Feb 02 '20 at 10:52

2 Answers2

1

You can redirect sys.stdout and use a StringIO object to catch the value:

import sys
from io import StringIO

something = lambda:print('I have been run')
old_stdout = sys.stdout
sys.stdout = catcher = StringIO()
exec('something()')
sys.stdout = old_stdout
print(catcher.get_value())

Or, for safety, you can use contextlib.redirect_stdout to do the same thing:

from contextlib import redirect_stdout
catcher = StringIO()
with redirect_stdout(catcher):
     exec('something()')
print(catcher.getvalue())
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
0

Hope it will be helpful to you.

Try the following:

b='a="jobid"\nprint(a)'
exec(b)
Michael Kemmerzell
  • 4,802
  • 4
  • 27
  • 43
Gomathi
  • 1
  • 2