Home > front end >  How do i run commands in the python interpreter from python itself?
How do i run commands in the python interpreter from python itself?

Time:10-06

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?

CodePudding user response:

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

CodePudding user response:

i don know why you want to run a python code inside your python script, but the way you can do it is with the -c parameter.

os.system("""python -c  "print('Hello world!')" """ )

or running inside a subprocess like so:

import subprocess

proc = subprocess.Popen('python', stdin=subprocess.PIPE, shell=True)
proc.communicate('print("hello world")\n')

CodePudding user response:

In your terminal you can enter "python" to launch the shell.

---@----desktop:~/Documents$ python
Python 3.8.10 (default, Jun  2 2021, 10:49:15) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello world")
hello world

Enter exit() to leave.

  • Related