Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I permanently store commands in the Python REPL/prompt?

Is there a way to store commands in Python?

For example, to store a bash command I can put:

# in .bash_profile
alias myproject="cd /path/to/my/project"

$ project

Is there a way to store a command, for example something like this:

'store' profile="from userprofile.models import Profile"

>>> profile

which will work in the Python command prompt whenever/wherever it is opened? Thank you.

like image 979
David542 Avatar asked Aug 21 '11 00:08

David542


People also ask

Which of the following is a python REPL environment?

Python interpreter shells such as IDLE, IPython, Jupyter notebook are REPL environments.

Does Python have a REPL?

Python provides a Python Shell, which is used to execute a single Python command and display the result. It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the command, prints the result, and loop it back to read the command again.

Which shell commands can be used on the command line to start the Python interactive shell in Windows?

To start the Python language shell (the interactive shell), first open a terminal or command prompt. Then type the command python and press enter.


1 Answers

In Bash, I'm assuming you are defining this aliases in .profile, .bash_rc or a similar file. In that file, add the line

export PYTHONSTARTUP=~/.python_rc.py

This will allow you to create a .python_rc.py file that is included whenever you start a session in the Python prompt/REPL. (It will not be included when running Python scripts, becasue it could be disruptive to do so.)

Inside that file, you could define a function for the command you want to save. In your case what you're doing is actually a touch more complicated than it seems, so you'd need to use a few more lines:

def profile():
    global Profile
    import sys
    if "path/to/your/project" not in sys.path:
        sys.path.append("path/to/your/project")
    from userprofile.models import Profile

After doing this, you'll be able to call profile() to import Profile in the Python prompt.

like image 197
Jeremy Avatar answered Sep 19 '22 01:09

Jeremy