5
5
----------
6
6
问题
7
7
----------
8
- You would like to customize Python’s import statement so that it can transparently load
9
- modules from a remote machine.
8
+ 你想自定义Python的import语句,使得它能从远程机器上面透明的加载模块。
10
9
11
10
----------
12
11
解决方案
13
12
----------
14
- First, a serious disclaimer about security. The idea discussed in this recipe would be
15
- wholly bad without some kind of extra security and authentication layer. That said, the
16
- main goal is actually to take a deep dive into the inner workings of Python’s import
17
- statement. If you get this recipe to work and understand the inner workings, you’ll have
18
- a solid foundation of customizing import for almost any other purpose. With that out
19
- of the way, let’s carry on.
13
+ 首先要提出来的是安全问题。本届讨论的思想如果没有一些额外的安全和认知机制的话会很糟糕。
14
+ 也就是说,我们的主要目的是深入分析Python的import语句机制。
15
+ 如果你理解了本节内部原理,你就能够为其他任何目的而自定义import。
16
+ 有了这些,让我们继续向前走。
20
17
18
+ 本节核心是设计导入语句的扩展功能。有很多种方法可以做这个,
19
+ 不过为了演示的方便,我们开始先构造下面这个Python代码结构:
21
20
22
- At the core of this recipe is a desire to extend the functionality of the import statement.
23
- There are several approaches for doing this, but for the purposes of illustration, start by
24
- making the following directory of Python code:
25
-
26
- .. code-block :: python
21
+ ::
27
22
28
23
testcode/
29
24
spam.py
@@ -32,8 +27,8 @@ making the following directory of Python code:
32
27
__init__.py
33
28
blah.py
34
29
35
- The content of these files doesn’t matter, but put a few simple statements and functions
36
- in each file so you can test them and see output when they’re imported. For example:
30
+ 这些文件的内容并不重要,不过我们在每个文件中放入了少量的简单语句和函数,
31
+ 这样你可以测试它们并查看当它们被导入时的输出。例如:
37
32
38
33
.. code-block :: python
39
34
@@ -58,11 +53,10 @@ in each file so you can test them and see output when they’re imported. For ex
58
53
# grok/blah.py
59
54
print (" I'm grok.blah" )
60
55
61
- The goal here is to allow remote access to these files as modules. Perhaps the easiest way
62
- to do this is to publish them on a web server. Simply go to the testcode directory and
63
- run Python like this:
56
+ 这里的目的是允许这些文件作为模块被远程访问。
57
+ 也许最简单的方式就是将它们发布到一个web服务器上面。在testcode目录中像下面这样运行Python:
64
58
65
- .. code-block :: python
59
+ ::
66
60
67
61
bash % cd testcode
68
62
bash % python3 -m http.server 15000
@@ -71,6 +65,7 @@ run Python like this:
71
65
Leave that server running and start up a separate Python interpreter. Make sure you can
72
66
access the remote files using urllib. For example:
73
67
68
+
74
69
.. code-block :: python
75
70
76
71
>> > from urllib.request import urlopen
0 commit comments