简体   繁体   中英

print greeting message when entering python interpreter

How do I print a greeting message when I initialize a python interpreter? For example, if I were to initialize a python interpreter with custom pre-defined variables , how might I advertise those variables to the user?

There is an environment variable called PYTHONSTARTUP that describes a path to a Python file to be executed on the invocation of Python shell. The script can contain normal Python code that is executed on invocation, therefore variables, prints or whatever else you want. It can be set in your ~/.bashrc

export PYTHONSTARTUP="$HOME/.pythonrc"

and then creating the file itself

cat > ~/.pythonrc << EOF
print 'Hello World!'
EOF

The output when starting python then looks somewhat like this

Python 2.7.8 (default, Oct 19 2014, 16:02:00)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Hello World!
>>>

Because it is a normal Python file, setting the variables and showing them/announcing availability can be done like this:

foo = 'Hello'
bar = 12.4123

print 'The following variables are available for use\nfoo: {}\nbar: {}'.format(foo, bar)

Output when invoking a Python repl and printing variable foo :

Python 2.7.8 (default, Oct 19 2014, 16:02:00)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
The following variables are available for use
foo: Hello
bar: 12.4123
>>> print foo
Hello

iPython acts different in a sense that it does not execute your PYTHONSTARTUP file, but has it's own mechanism called profiles. Default profile can be modified in ~/.ipython/profile_default/startup/ , where each *.py and *.ipy file is executed (see ~/.ipython/profile_default/startup/README ).

You can embed a console from a script using the built-in console or IPython's console.

If you want to use Python's built-in console , pass the banner argument. Assuming you have a dictionary of variables to inject:

from code import interact
vars = {'hello': 'world'}
message = 'Extra vars: {}'.format(', '.join(vars))
interact(banner=message, local={'hello': 'world'})

With IPython's console , pass banner1 .

from IPython import embed
embed(banner1=message, user_ns={'hello': 'world'})

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