python自动导入包_运行python脚本时自动导入模块?

I think other may ask this before but I cannot find it. My question is, I have these statements in my .ipython/ipy_user_conf.py:

ip.ex('import matplotlib as mat')

ip.ex('import matplotlib.pyplot as plt')

ip.ex('import numpy as np')

ip.ex('import pupynere as pu')

ip.ex('import g')

ip.ex('import bsite')

ip.ex('import csvf')

ip.ex('import pandas as pa')

ip.ex('import pickle as pk')

ip.ex('import mathex as mathex')

ip.ex('import os as os')

ip.ex('import re as re')

ip.ex('import scipy as sp')

ip.ex('import mpl_toolkits.basemap as bmp')

ip.ex('from mpl_toolkits.basemap import cm')

Then If I use python in ipython shell, these modules will be loaded directly when I start ipython, but if I have a python script, eg., ba_plot.py used to make some plots. I debugged the script by an interactive way in the ipython, but then I want to run it within the shell terminal, like:

chaoyue@chaoyue-Aspire-4750:~$ python ba_plot.py

but before this, each time I need to copy at the beginning of ba_plot.py file the following again:

import matplotlib as mat

import matplotlib.pyplot as plt

import numpy as np

import pupynere as pu

import g

import bsite

import csvf

import pandas as pa

import pickle as pk

import mathex as mathex

import os as os

import re as re

import scipy as sp

import mpl_toolkits.basemap as bmp

from mpl_toolkits.basemap import cm

Because otherwise it will complain it cannot find the module. So, is there anyway that I can avoid do this by including some header file at the beginning of my python script while in the header file all these modules are imported? By this way, I need only to add on line at the beginning of my python script.

解决方案

It's bad practice to have a script which depends on an external startup script to make it work. Doing these imports is how you should do it.

You could simplify it if you regularly import a fairly large set of things by centralising your imports in a file (call it common_imports.py, for example), and then importing all from that (from common_imports import *). That then becomes only one line to put in. I would still prefer to see explicit imports, however.

(Another note: in import os as os, the as os is entirely superfluous.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值