Auto import modules on live template application in pycharm

Hello JetBrains community. I found a similar post in the forum, but applies to the IntelliJ IDE.

 

I would like the PyCharm IDE to automatically import modules that are used in my custom Live Templates. Is this functionality available? How do you do it?

 

Here is an example of a Live Template I am making for setting up an instance of the logging module.

max_log_bytes = $MAX_LOG_SIZE$
backup_count = $MAX_LOG_BKUP$
logging_level = logging.$LOG_LEVEL$

date_format = '%Y-%m-%d %H:%M:%S'
message_format = '%(asctime)s.%(msecs)03d|%(levelname)s|%(threadName)s(%(thread)d)|%(name)s|(%(funcName)s):-%(message)s'
script_name = '{}'.format(__file__.split('/')[-1].split('.')[0])
log_path = '{}/log'.format(os.path.dirname(sys.argv[0]))
if not os.path.exists(log_path):
os.makedirs(log_path)

$LOGGER_VAR$ = logging.getLogger(script_name)
stream_handler = logging.StreamHandler()
rotating_file_handler = logging.handlers.RotatingFileHandler(r'{}/{}.log'.format(log_path, script_name), mode='a',
maxBytes=max_log_bytes, backupCount=backup_count)
formatter = logging.Formatter(datefmt=date_format, fmt=message_format)

stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging_level)

rotating_file_handler.setFormatter(formatter)
rotating_file_handler.setLevel(logging_level)

$LOGGER_VAR$.setLevel(logging_level)
$LOGGER_VAR$.addHandler(stream_handler)
$LOGGER_VAR$.addHandler(rotating_file_handler)$END$

 

I would expect the following import statements:

import logging.handlers
import os
import sys

 

Thanks in advance for your time and help!

 

1 comment

Hi,

Have you considered using Auto Import?

https://www.jetbrains.com/help/pycharm/settings-auto-import.html#dda351f1

 

After you insert live template into your code, you can run code inspection with alt+shift+i, and it will offer you to insert missing imports, which you can quickly apply with alt+enter

Let me know if this doesn't answer your question.

0

Please sign in to leave a comment.