Интерактивные режим Python

Содержание
Начало работы
Инструкция import в интерактивном режиме
Импортировать несколько функций
Импортировать все функции
Похожие статьи

Начало работы

Если у вас уже установлен Python - для перехода в интерактивный режим достаточно ввести команду

python

без аргументов

Для Windows можно скачать и установить интерпретатор Python.

Ваша директория www.andreyolegovich.ru
Интерактивный режим
www.andreyolegovich.ru

знаки >>> говорят о том, что мы работаем в интерактивном режиме а не запускаем программы из файла.

Если перед сообщением нет знаков >>> или … , то это сообщение выведено интерпретатором. Например, на картинке выше, выводом интерпретатора является предпоследняя строчка Be careful no to fall off!

Троеточие означает, что строка является продолжением многострочной инструкции.

Чтобы начать вводить инструкцию на следующей строке нужно поставить в конце первой инструкции двоеточие. Обратите внимание на пример, после слова the_world_is_flat стоит :

Чтобы завершить многострочную инструкцию нажмите Enter дважды.

Инструкция import в интерактивном режиме

Если у Вас не получается применить инструкцию import возможно Вы и модуль сейчас находитесь в разных директориях. Выполните следующие команды:

import os
os.getcwd()

Ваша директория www.andreyolegovich.ru
os.getcwd
www.andreyolegovich.ru

Python выведет на экран активную в данный момент директорию. Если модуль лежит не там, найдите его директорию и перейдите в неё командой

os.chdir('C:\\Users\\andreyolegovich\\python')

Ваша директория www.andreyolegovich.ru
os.getcwd
www.andreyolegovich.ru
Ваша директория www.andreyolegovich.ru
os.getcwd
www.andreyolegovich.ru

Рассмотрим скрипт sample.py

def say_hello(): print("Hello!") def display_name(): print(f"Имя первого модуля: {__name__}") if __name__ == "__main__": display_name()

Перейдём в интерактивный режим

python

Python 3.9.5 (default, Jun 15 2021, 15:30:04) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.

>>> import sample
>>> sample.say_hello()

Hello!

Если выполнен импорт всего модуля, обратиться к функции напрямую (то есть без указания модуля как в прошлом примере) не получится

>>> say_hello()

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

Можно импортировать сразу функцию, и тогда указывать модуль при вызове не нужно

>>> from sample import say_hello
>>> say_hello()

Hello!

Рассмотрим скрипт words.py из курса от Pluralsight

from urllib.request import urlopen def fetch_words(): story = urlopen("http://sixty-north.com/c/t.txt") story_words = [] for line in story: line_words = line.decode("utf8").split() for word in line_words: story_words.append(word) story.close() return story_words def print_words(story_words): for word in story_words: print(word) def main(): words = fetch_words() print_words(words) if __name__ == "__main__": main()

python

Python 3.9.5 (default, Jun 15 2021, 15:30:04) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.

Импортировать несколько функций

>>> from words import(fetch_words, print_words)
>>> print_words(fetch_words())

It was

Импортировать все функции

>>> from words import *
>>> fetch_words()

'It', 'was', 'the', 'best', 'of', 'times', 'it', 'was', 'the', 'worst', 'of', 'times', 'it', 'was', 'the', 'age', 'of', 'wisdom', 'it', 'was', 'the', 'age', 'of', 'foolishness', 'it', 'was', 'the', 'epoch', 'of', 'belief', 'it', 'was', 'the', 'epoch', 'of', 'incredulity', 'it', 'was', 'the', 'season', 'of', 'Light', 'it', 'was', 'the', 'season', 'of', 'Darkness', 'it', 'was', 'the', 'spring', 'of', 'hope', 'it', 'was', 'the', 'winter', 'of', 'despair', 'we', 'had', 'everything', 'before', 'us', 'we', 'had', 'nothing', 'before', 'us', 'we', 'were', 'all', 'going', 'direct', 'to', 'Heaven', 'we', 'were', 'all', 'going', 'direct', 'the', 'other', 'way', 'in', 'short', 'the', 'period', 'was', 'so', 'far', 'like', 'the', 'present', 'period', 'that', 'some', 'of', 'its', 'noisiest', 'authorities', 'insisted', 'on', 'its', 'being', 'received', 'for', 'good', 'or', 'for', 'evil', 'in', 'the', 'superlative', 'degree', 'of', 'comparison', 'only']

>>> print_words()

Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: print_words() missing 1 required positional argument: 'story_words'

>>> print_words("test")

t e s t

>>> main

<function main at 0x7f876a266820>

>>> main()

It was the

Ещё один пример работы в интерактивном режиме можно изучить в статье sys.argv[]