我有一个带有库的 python .py 文件,我想在启动时将它加载到我的环境中,而不必每次都单独加载它。
例如我目前需要逐行加载 numpy、matlab 导入等,是否无法从 >>> 提示符准备好加载几个文件。我试过运行 python3 <> 但它不起作用。
这是我的 .py 文件是不是我做错了什么。
# Load libraries
import sys
#import OS
import pandas
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
import pandas as pd
from datatime import datetime
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn import datasets
import scipy.stats as stats
import pylab
请您参考如下方法:
您要查找的文件称为启动文件。
在继续之前:你真的应该考虑使用 jupyter或者至少是 ipython一部分。它具有更强大的功能来设置自定义交互环境——以及更强大的交互环境。例如,您可以指定一个充满脚本的目录,而不是单个脚本,或不同的命名配置文件,或者您甚至可以让它在第一次使用时自动导入模块,而不是等待它们为每个 session 加载,无论您是否需要他们与否 - 这真的只是触及表面。
但是,假设您坚持使用默认的交互式环境。
环境变量PYTHONSTARTUP允许您指定仅在交互模式下运行的启动文件:
If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts
sys.ps1andsys.ps2and the hooksys.__interactivehook__in this file.
因此,在您的主目录、virtualenv 或其他任何合适的地方创建一个文件,如下所示:
import sys
import os
import pandas
# etc.
然后设置环境变量指向那个文件。当然,具体的实现方式取决于您使用的平台(以及您使用的 shell)、文件的存储位置,以及您是否希望每次登录时自动发生。
举个例子,假设你在 Linux 上,使用 bash,你没有使用虚拟环境,你将文件作为 .pythonstartup.py 放在你的主目录中,然后你希望它在每次登录时发生。然后你会把它放在你的个人资料中:
export PYTHONSTARTUP="$HOME/.pythonstartup.py"
现在,启动一个新的 shell,每次运行 Python 时,它都会启动所有这些导入:
$ python3
>>> print(sys.version_info)
sys.version_info(major=3, minor=6, micro=4, releaselevel='final', serial=0)
