-1

Problem:

I want to access the python interpreter from python code, and run commands in it. Currently i (naively) do the following:

import os
os.system("python3") # open the python interpreter
os.system("Hello World!") # print Hello World! via interpreter 

However, when this code is run the following happens in the command line: the python interpreter starts but does not print "Hello World!" yet, because it sees Hello World! as a separate command that gets executed in the command line and not in the interpreter.

Question:

How do i make "Hello World!" print in the interpreter directly via python?

2 Answers2

0

I think pexpect will meet your requirements.

#!/usr/bin/env python3

import pexpect

c = pexpect.spawnu('/usr/bin/env python3')

c.expect('>>>')
print(c.before)
print(c.after, end='')
c.sendline('"Hello Python!"')
c.interact()
emptyhua
  • 6,634
  • 10
  • 11
-1

You can use

os.system("""python -c  "print('hello')" """ )

In this way it will send to the cmd the following instruction

python -c  "print('hello')"

If you put the -c flag it will run the code "print(hello)" or whatever you put inside. The use of """ """ is to make sure the string gets declared properly

Also there is more info here Run function from the command line

Victor
  • 398
  • 1
  • 2
  • 11
  • This is good for simple code like hello world but this does not work if you for example want to save variables etc. where the interpreter comes in handy. – hello_world2022 Oct 05 '21 at 15:43