[英]How to create a python script that import other imports
I would like to create a file that import other imports, eg 我想创建一个导入其他导入的文件,例如
startup.py: startup.py:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('qt5agg')
...
the just write 只是写
import startup
and have all of them. 并拥有所有这些。
is it possible? 可能吗?
It's not recommended for readability, but you could write: 不建议出于可读性考虑,但可以这样写:
from startup import *
in the file where you want to use np
etc. 在您要使用
np
等的文件中
Check out this older StackOverflow post which details many different ways to achieve what you want, and especially the excellent comment by 'Eric Leschinski'. 请查看此较早的StackOverflow帖子,其中详细介绍了实现所需内容的多种方法,尤其是“ Eric Leschinski”的出色评论。
The simplest solution I'd check out first is to make a new directory and declare it as a package by creating an __init__.py
file in there, which would contain the imports. 我首先要检查出的最简单的解决方案是创建一个新目录,并通过在其中创建
__init__.py
文件(包含导入内容)将其声明为包。
This dummy "package" of yours will be the input handler, and then from your main script you would from root.parent.folder.file import class/variable/whatever
. 您的这个虚拟“包”将作为输入处理程序,然后从您的主脚本中
from root.parent.folder.file import class/variable/whatever
。 The main drawback is that this disallows non-relative paths, but it's okay if all the project is self-contained. 主要缺点是,这不允许非相对路径,但是如果所有项目都是独立的就可以。
I suggest you explicitly specify module that you wanted to be imported at the time of star import :) 我建议您在星号导入时明确指定要导入的模块:)
Try the following example: 请尝试以下示例:
#example.py
import time
import random
import collections
__all__ = ['time', 'random']
$ python
>>> from example import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'random', 'time']
See how it didn't import collections
module, because i didn't ask it to :) 看看它没有导入
collections
模块,因为我没有要求它:)
You could do something like this 你可以做这样的事情
startup.py startup.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
np = np
plt = plt
matplotlib = matplotlib
main.py main.py
from startup import *
plt.show()
It's kinda ugly in my opinion, but works. 在我看来,这有点丑陋,但是可行。
You can try following: 您可以尝试以下操作:
Let file1 is abc.py 假设file1为abc.py
import pandas as pd
import numpy as np
Let file2 is main.py : 让file2为main.py :
import abc
# Use pandas import as temp.pd
df = temp.pd.DataFrame({'A': [1,2,3], 'B': [2,3,4]})
print(df)
Output: 输出:
A B
0 1 2
1 2 3
2 3 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.