简体   繁体   中英

Setting startup script in PyCharm debugger console

In PyCharm, it is possible to set a script that runs upon opening a new console (through Settings -> 'Build, Execution, Deployment' -> Console -> Python Console -> Starting script).

Is there a way to similarly apply a startup script to the debugger console? I find myself importing the same packages over and over again, each time I run the code.

When you run Python Console inside PyCharm, it executes custom PyCharm script at <PYCHARM_PATH>/plugins/python/helpers/pydev/pydevconsole.py .

On the other hand, when you run PyCharm Debug Console while debugging, it executes custom PyCharm script at <PYCHARM_PATH>/Plugins/python/helpers/pydev/pydevd.py with command line parameter --file set to script you are debugging.

You can modify pydevd.py file if you want ( Apache 2 license ), but the easier approach would be to create startup script in which you import modules you need, functions and such and import ALL while inside PyCharm Debug Console . This would reduce all your imports to one.

Walkthrough:

Let's create 2 files:

  • main.py - Our main script which we will debug
  • startup.py - Modules, functions or something else that we would like to import.

main.py content:

sentence = 'Hello Debugger'


def replace_spaces_with_hyphens(s):
    return s.replace(' ', '-')


replace_spaces_with_hyphens(sentence) # <- PLACE BREAKPOINT!

When breakpoint is hit, this is what we have inside scope:

堆

If you always find yourself importing some modules and creating some functions, you can define all that inside startup.py script and import everything as from startup import * .

startup.py :

# Example modules you always find yourself importing.
import random
import time

# Some function you always create because you need it.
def my_imported_function():
    print("Imported !")

Inside Python Debugger Console, use from startup import * as mentioned above and you would see all modules and function inside scope, ready for use.

调试导入

you could just create a new debug configuration (run > edit configurations) and point it to a script in your project (eg called debug.py that you gitignore). Then when you hit debug it will run that script and drop you into a console.

Personally, I prefer to just launch ipython in the embedded terminal than using the debug console. On linux, you can create a bash alias in your .bashrc such as alias debug_myproject=PYTHONSTARTUP=$HOME/myproject/debug.py ipython . Then calling debug_myproject will run that script and drop you into an ipython console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM