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!
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!
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.
Recommended Posts