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.
Python interpreter shells such as IDLE, IPython, Jupyter notebook are REPL environments.
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.
To start the Python language shell (the interactive shell), first open a terminal or command prompt. Then type the command python and press enter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With