![](/img/trans.png)
[英]Automatically import modules when entering the python or ipython interpreter
[英]print greeting message when entering python interpreter
有一個名為PYTHONSTARTUP
的環境變量,它描述了在Python shell調用時要執行的Python文件的路徑。 該腳本可以包含在調用時執行的普通Python代碼,因此可以包含變量,打印或其他任何您想要的代碼。 它可以在你的〜/ .bashrc中設置
export PYTHONSTARTUP="$HOME/.pythonrc"
然后創建文件本身
cat > ~/.pythonrc << EOF
print 'Hello World!'
EOF
啟動python時的輸出看起來有點像這樣
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!
>>>
因為它是一個普通的Python文件,所以設置變量並顯示它們/宣布可用性可以這樣做:
foo = 'Hello'
bar = 12.4123
print 'The following variables are available for use\nfoo: {}\nbar: {}'.format(foo, bar)
調用Python repl和打印變量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在某種意義上表現不同,它不會執行您的PYTHONSTARTUP文件,而是擁有自己的稱為配置文件的機制。 可以在~/.ipython/profile_default/startup/
修改默認配置文件,其中執行每個*.py
和*.ipy
文件(請參閱~/.ipython/profile_default/startup/README
)。
您可以使用內置控制台或IPython控制台從腳本嵌入控制台。
如果要使用Python的內置控制台 ,請傳遞banner
參數。 假設你有一個要注入的變量字典:
from code import interact
vars = {'hello': 'world'}
message = 'Extra vars: {}'.format(', '.join(vars))
interact(banner=message, local={'hello': 'world'})
使用IPython的控制台 ,傳遞banner1
。
from IPython import embed
embed(banner1=message, user_ns={'hello': 'world'})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.