将.py文件预加载到Python3环境中

2024-04-24 00:45:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有库的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

Tags: 文件frompyimportgtpandasmodelmatplotlib
1条回答
网友
1楼 · 发布于 2024-04-24 00:45:20

你要找的是一个启动文件。你知道吗


在进一步讨论之前:您真的应该考虑使用^{}或者至少是它的^{}部分。它有更强大的功能来建立一个自定义的交互环境,以及一个更强大的交互环境放在首位。例如,您可以指定一个充满脚本的目录,而不是一个脚本或不同的命名配置文件,或者您甚至可以让它在第一次使用时自动导入模块,而不是在每个会话中等待加载所有模块,无论您是否需要它们,这只是表面现象。你知道吗

但是,让我们假设您坚持使用默认的交互环境。你知道吗


环境变量^{}允许您指定仅在交互模式下运行的启动文件:

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.ps1 and sys.ps2 and the hook sys.__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)

相关问题 更多 >