PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

[FIXED] How to get the python interactive shell output of a python code in a variable?

 August 17, 2022     io, output, python, python-interactive     No comments   

Issue

Suppose I have

code = '2+3'

I want to run this code in python interactive shell and get the output string in a variable. So the result of the execution of code would be stored in another variable called output

In this case, the output variable would be '5'.

So is there any way to do this?

def run_code(string):
    # execute the string
    return output # the string that is given by python interactive shell

!!! note:

  exec returns None and eval doesn't do my job

Suppose code = "print('hi')" output should be 'hi'

Suppose code = 'hi' output should be

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'hi' is not defined 

Solution

if you really must run strings as python code, you COULD spawn another python process with the subprocess.Popen function, specify stdout, stderr, stdin each to subprocess.PIPE and use the .communicate() function to retrieve the output.

python takes a -c argument to specify you're giving it python code as the next argument to execute/interpret.

IE python -c "print(5+5)" will output 10 to stdout

IE

proc = subprocess.Popen(["python", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
print(stdout.decode('utf-8'))


Answered By - JackofSpades
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing