Run the Python interpreter in a script

To run the Python interpreter in a script

Have you ever wanted to ** run an interpreter in a Python script **? You can use the functions and classes you created from the beginning, and you can also execute ordinary Python code. Isn't it nice!

Basics

In Python, there is a ** standard library ** called code.py that can run the interpreter.

myconsole.py


import code
console = code.InteractiveConsole(locals=locals()) # <- locals=locals()Important
console.interact()

Write like this. Here, code.InteractiveConsole is given the argumentlocals = locals (), but locals () is a ** function that returns all the values of the variables in the ** local area of itself (here in the script) in dictionary format. By giving this as an argument, ** functions in the script etc. are passed to the started python interpreter **

When you run this script,

$ python myconsole.py
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

This is how the Python interpreter runs!

Advanced version

I used this code.py this way.

color.py


import code


def split_code(colorcode, sep=2):

    for index, letter in enumerate(colorcode, start=1):
        if index == 1:
            continue

        elif index % sep == 0:
            yield colorcode[index-sep:index]


def get_rgb(colorcode):

    result = []

    for element in split_code(colorcode):
        result.append( int(element, 16) )

    return result

def get_colorcode(r, g, b):

    code = hex(r) + hex(g) + hex(b)

    result = list(split_code(code))

    return "".join(result[1::2])


if __name__ == "__main__":

    code.InteractiveConsole(locals=locals()).interact()

This python script has a function to convert the color code. When I run this script ...

$ python color.py
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'split_code', 'code', 'get_colorcode', 'get_rgb']
>>>

In this way, the Python interpreter is started, and you can use the created function ** without importing anything. The reason you don't have to import anything is because the above code says locals = locals ().

If you didn't set locals = locals () here,

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dir()
['__builtins__', '__doc__', '__name__']
>>>

This makes it impossible to use the functions in the script.

Reference link

Recommended Posts

Run the Python interpreter in a script
Run a multi-line script in a PDB
Get the script path in Python
Run a simple algorithm in Python
Write the test in a python docstring
Let's run a Bash script in Java
How to run a Maya Python script
Create a shell script to run the python file multiple times
Run a Python script from a C # GUI application
[Python] Get the files in a folder with Python
Get the caller of a function in Python
Make a copy of the list in Python
Until you run the changefinder sample in python
[Mac] Run the RealSense D415 sample in Python
Call a Python script from Embedded Python in C ++ / C ++
Output in the form of a python array
[Python] Find the transposed matrix in a comprehension
Run a python script from excel (using xlwings)
Check if the string is a number in python
Take a screenshot in Python
Create a function in Python
A solution if you accidentally remove the python interpreter in / usr / local / bin /.
Download the file in Python
Run automatic jobs in python
Find the difference in Python
Run shell commands in python
Run Python unittests in parallel
Run illustrator script from python
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
What's in that variable (when running a Python script)
Make a bookmarklet in Python
Write a log-scale histogram on the x-axis in python
Draw a heart in Python
Run a Python file with relative import in PyCharm
A reminder about the implementation of recommendations in Python
What does the last () in a function mean in Python?
Run the output code with tkinter, saying "A, pretending to be B" in python
I replaced the Windows PowerShell cookbook with a python script.
Find out the apparent width of a string in python
How to run a Python program from within a shell script
How to use the __call__ method in a Python class
Change the standard output destination to a file in Python
Let's create a script that registers with Ideone.com in Python.
A note for embedding the scripting language in a bash script
Note 2 for embedding the scripting language in a bash script
Get the number of specific elements in a python list
Creating a Python script that supports the e-Stat API (ver.2)
Process the files in the folder in order with a shell script
Do something like a Python interpreter in Visual Studio Code
[Note] Import of a file in the parent directory in Python
How to get the last (last) value in a list in Python
After enabling the python virtual environment in the batch file, run the python file
A set of script files that do wordcloud in Python3
Find the eigenvalues of a real symmetric matrix in Python
A Python script that compares the contents of two directories
I wrote a script that splits the image in two
Maybe in a python (original title: Maybe in Python)
Write a binary search in Python
[python] Manage functions in a list
Hit a command in Python (Windows)