Python development with Eclipse and Ant

Python is a very flexible and powerful dynamic scripting language, with a complete object-oriented features. Many supporters point out, Python language compared to other languages ​​faster and more effectively express their intentions. But from Java ™ or Microsoft® .NET technology just go to the Python people will find, feature-rich and sophisticated IDE and development tools are gone. Those developers will find solutions from their familiar Java development tools. This paper describes how to use Python development tools based on the popular Eclipse and Ant Java technology.

Brief introduction

Over the years, there has been a lot of cross-pollination between the Java language and Python phenomenon camp. Prominent example might be Jython in this regard. This is a pure Python runtime environment using Java. According to this statement, you will study how to build and deploy Python development tools with Eclipse IDE and Ant. Eclipse and Ant is very popular tool, which features rich, scalable, and open source; Python also has the same quality. PyDev and PyAntTasks are extending Eclipse and Ant, with the tools they can use these Java developers Python. This paper required for installation from download tool and the extended start with. To explain how to use Eclipse and Ant Python development, I will read RSS feeds with actual code example Python.

This article does not involve Eclipse, Ant, Python details. Depth discussion about these topics, see  the Resources  link one in.

Support for Python

This article uses the software tested in CPython 2.3. Apart from a few exceptions, you should be able to run Jython. Of particular note, PyDev debugger does not currently support Jython. Another difference is performed by Jython script into interactive mode after running from PyDev, so you must manually kill. Jython PyDev editor compatible with source code, Python Ant tasks and Jython compatible addition py-doc task.

 

blue_rule.gif
c.gif
c.gif
u_bold.gif
Back to top

 

 

Use Eclipse for Python development

Eclipse Overview

Eclipse is a Java technology integrated development environment, developed by IBM, and to open up its source code. It is the foundation of IBM Software WebSphere Application Development environment and a variety of other tools. Eclipse developer community is very active, they not only develop Eclipse itself, but also the development of a large number of plug-ins for Eclipse use. About Eclispe and Eclipse plug-ins Web site, see  Resources  for a link section. Although traditionally Eclipse is a Java development tool, but some exist in other languages makes the development of plug-in Eclipse program is made possible, such as C / C ++, Python and Perl.

In Eclipse, the source code is organized into a project (Project) in. Items can be loaded, unloaded and import. Eclipse structure into the user interface to view (View) and the editor (Editor). Examples of view and the editor comprising: a source code outline view, Java source code editor, Python and a source code editor navigation file system view. Eclipse user interface is the most critical concept is the implied  perspective (Perspective by) . It is a perspective view of a group of commonly used together when performing certain types of activities. Standard Eclipse perspective include: Debug, Java Browsing, Java, Java Type Hierarchy, Plug-in Development, CVS Repository Exploring, Resource and Install / Update. Separate Python perspective does not currently exist. When making Python development, I usually use the Resource perspective and Debug perspective.

Install PyDev

First, download from the Eclipse Web site Eclipse (See  Resources for  a link in a), and depending on your platform, follow the installation guide to install Eclipse:

Eclipse update mechanism makes it easier to install PyDev plugin. Select from Eclipse  Help> Software the Updates> Update Manager , start the Install / Update perspective. In the Feature Updates view in the lower left corner, PyDev plugin will update the site as the new Site Bookmark added to the "Sites to Visit" folder. Eclipse's PyDev update site URL is http://pydev.sf.net/updates/. Now, Feature Updates editor should show "PyDev" this feature. In Feature Updates editor, expand PyDev> Other , wherein selection of PyDev display (should be at least 0.4.1). Then select "Install Now" to install the characteristic. Download the PyDev Eclipse plug-ins, and install it in Eclipse.

Import sample project

To access this project using the sample code can be downloaded zip file (see  Resources section), expand the zip file in the file system, and then import the project at Eclipse. Import project is to switch to the Resource perspective, select  File> Import , then select "Existing Project into Workspace", and then select the location you expand the zip file. At this time, Navigator view feedParserTest project should appear.

Sample project has been included in the Universal Resource Fead Parser parsing library, which is published by Python open-source license agreement. For links Feed Parser project Web site, see  the Resources  section.

 

blue_rule.gif
c.gif
c.gif
u_bold.gif
Back to top

 

 

PyDev roaming

Now beginning to learn how to understand the characteristics of the project by PyDev imported. PyDev is in the process of developing, but already very efficient Python development environment. PyDev now includes the following features:

  • Contains Python Python syntax highlighting editor features.
  • Parsing Python, and displays an error in Python editor and highlight the Tasks view.
  • You can convert tabs to spaces option.
  • Outline view shows the introduced library classes and functions.
  • Python stack trace information terminal can view a hyperlink to the source code.
  • Hyperlink to an internal source; import function call within the same module can navigate via hyperlinks.
  • The ability to run Python scripts from the Navigator view.
  • The debugger supports breakpoints, step through the code values ​​and display of variables.

PyDev Options window

By  Window> the Preferences , and select PyDev (see Figure 1), you can access PyDev options. The first set of options may change the way PyDev process tabs in the source code, can also change the color of the syntax element.


Figure 1. PyDev Options window
PyDev Options window 

Set Python interpreter

PyDev Debug option to choose Python interpreter for the implementation of Python code. If you can not find the PyDev Python interpreter, or want to use another interpreter, can be set here (see Figure 2).


Figure 2. PyDev Debug Options
PyDev Debug Options 

Source code

我的大部分 Python 工作都是在 Resource 视角中完成的。使用方法是先切换到 Resource 视角,然后在左上角的 Navigator 视图中双击 feedParserTest/src/feedparserTest/FeedparserTest.py 文件。Python 编辑器打开该文件,对 Python 语法进行解析,完成设置颜色和语法检查的工作(请参阅图 3)。


图 3. Python 编辑器
Python Editor 

如果源代码中有任何错误,则显示在右下角的 Tasks 视图中显示出来。双击 Tasks 视图中的错误,便可找到那条讨厌的代码行。

Outline 视图在左下角,其中用一种便于浏览的结构显示出当前正在编辑的文件。导入的库、类、函数全都显示出来,通过双击 Outline 视图中的项目,便可以实现导航。PyDev 在编辑 Python 文件的过程中对齐进行预先解析的工作,同时更新 Outline 视图,执行语法检查,并用不同颜色显示语法元素。

编辑器的特性

PyDev 0.4 版在 Python 源代码编辑器中为函数和导入库加入了超链接的特性。如果在越过某项导入或函数调用(必须在 PYTHONPATH 目录中)的同时按下 Control 键,PyDev 就能显示出一个超链接,这样您可以在导入库或函数的源代码之间导航。请注意,为了在您自己的源代码中跨模块使用该特性(从一个模块链接到另一个模块),必须修改 PYTHONPATH 环境变量,在其中加入这些模块,这样 PyDev 就可以找到它们了。

人们已经开始将一些优异的源代码编辑特性加入最新版本的 PyDev 中,其中就包括代码块注释与取消注释,以及代码左右移位(请参阅图 4)。


图 4. PyDev 编辑器的其他特性
Other features PyDev editor 

运行 Python 脚本

如果不能执行代码,那么 IDE 也不是太有用。为执行 Python 代码,可从 Navigator 视图中选择 feedparser.py 文件,用右键点击,然后选择 Python > Run。随后会显示 Python 的启动配置窗口(请参阅图 5)。


图 5. Python 启动配置
Python launch configuration 

Python 启动配置窗口中可以定义脚本执行的当前目录,传递给脚本的参数,以及用哪一个 Python 解释器运行脚本。feedparser.py 以一个 RSS URL 作为参数,所以可在参数字段中填入 URL,如 http://www.ibm.com/developerworks/news/dw_dwtp.rss。其余的缺省定义就可以了,所以单击 Run

脚本执行时输出信息显示在 Console 窗口中。如果有错误出现,Console 窗口中将显示堆栈跟踪信息,其中的每一行都可以通过超链接找到 Python 源代码。

Python 调试器

Python 调试器是最近才加入 PyDev 插件中的。要使用调试器,可在 Python 编辑器中想中断的代码行的左侧点击,设置断点。在图 6 中,我在 feedparser.py 的 1830 行处设置了断点。然后在 Navigator 视图中选择这个 Python 模块,点击右键,选择“Python > Debug...”。这时将显示与前面相似的一个启动配置窗口。点击 Debug 进入 Debug 视角,同时启动调试器。


图 6. Python 调试器
Python Debugger 

左上角的 Debug 视图显示当前正在执行的进程和线程,右上角的 Variables 视图显示当前运行域中的所有变量,Python 编辑器会显示调试器目前停在哪条语句上,同时所有的输出信息都显示与 Console 视图中。调试器可以通过 Debug 视图底部的按钮或 Run 菜单进行控制。

其他 Eclipse 特性

Eclipse 及其插件还具备很多其他的特性,可应用于 Python 开发中,如 XML 编辑器、UML 编辑器(不过大多数是以 Java 代码为中心),还有资源控制方面的插件。目前 Eclipse 插件站点上列出的插件几乎有 500 个(请参阅 参考资料 一节中的相关链接)。我将着重介绍一个对很多 Python 开发人员都特别有用的插件:Eclipse 发行版中已经包括的 CVS 插件,不过不会讨论细节内容。

Eclipse 中包括特性丰富的集成 CVS:

  • 支持 SSH、pserver、ext 等连接方法。
  • 基本 CVS 命令的支持:检出项目、提交变更、更新、向.cvsignore 中增加文件或模式等等。
  • 文件合并查看。
  • 在源代码控制中实现对文件不同之处的比较。
  • 项目同步,并用资料库显示出删除和新增的内容。

还可以通过提供其他插件来支持其他源代码控制系统,如 ClearCase、Subversion、Visual SourceSafe 等。

 

blue_rule.gif
c.gif
c.gif
u_bold.gif
回页首

 

 

在 Eclipse 中使用 Python 的交互式 shell

Python 解释器支持 Python 代码的交互式执行。这种方式对于调试一段代码是非常有用的,因为不用把代码放进 Python 脚本中并执行脚本了。同时,Python 解释器的交互模式可以很容易地集成到 Eclipse 中。

要增加对 Python 交互式执行的支持,可通过 Run > External Tools > External Tools 增加一个 External Tool 启动程序。这时将打开 External Tool 启动程序配置窗口。在 Configurations 列表中选择“Program”,然后点击“New”创建一个新的配置。将该配置命名为诸如 "pythonInteractive" 之类,然后设置 Location,令其指向您的 Python 解释器,接着,将 "-i" 作为唯一的参数传递进来(请参阅图 7)。

在 Common 选项卡下,选中复选框,使该配置在 External Tools 收藏夹菜单中显示出来。


图 7. Python 交互方式配置
Python interactively configure 

要运行刚刚在 Eclipse 中创建的启动器,可选择 Run > External Tools > pythonInterpreter。Python 解释器的输出显示在 Console 视图中。Console 中可输入 Python 命令并执行,就像从命令行中执行 Python 一样。为导入并在交互模式下使用模块,您需要将模块的位置增加到 PYTHONPATH 环境变量中。

在 Eclipse Console 中执行 Python 与用命令行执行的不同之处在于,无法启用命令历史特性(通过向上和向下的方向键实现),因为 Eclipse Console 会自己解释这些键。

 

blue_rule.gif
c.gif
c.gif
u_bold.gif
回页首

 

 

在 Python 开发中使用 Ant

Python 会在它需要的时候自动编译模块。这意味着 Python 开发人员通常不必显式地对模块进行编辑。即便如此,有时候手工编译 Python 代码还是很有用的,同时,构建和部署过程中还有很多其他方面的内容可以自动化实现。这也正是构建工具的用武之地。

我将着重介绍来自 Java 编程世界中的 Apache Ant,这个工具可大量应用在 Python 开发中。Apache Ant 是 Java 编程领域内事实上的标准构建工具。它更加轻便,与 Java 技术结合得更好,可用于替代其他的构建工具。Ant 可以在支持 Java 编程语言的任何一种平台上运行。尽管我们需要的大多数构建特性 Ant 都已经提供了,但如果要将 Ant 用做 Python 构建工具,还是需要有一些关键的与 Python 相关的特性。我已经开发了若干定制的 Ant 插件(用 Ant 的行话讲叫做 task),可提供构建 Python 时需要的特定于 Python 的特性。

Ant 用 XML 作为描述构建的格式。build 文件组织为需要执行的目标。每一个目标都可能依赖于其他的目标。Ant 将根据您所请求执行的目标,以及一组依赖目标,来执行任何需要的目标。每一个目标都可能包含任意数量的 Ant 任务,而由 Ant 任务实际执行目标的工作。Ant 有很多内置的任务,可以完成诸如编译 Java 代码、生成文档、操纵文件和目录,同时第三方又提供了很多附加的任务。

安装 Python Ant 库

我将通过为 feedparser 项目创建构建脚本来介绍 Ant 构建脚本和 Python Ant 任务的基础知识。为了使用 Python Ant 任务,您需要下载并安装包含这些任务的 Java 库。首先,从 参考资料 一节中列出的 URL 中下载 Python Ant 任务库(pyAntTasks.jar)。然后,将 JAR 文件拷贝到 Eclipse 的 Ant 插件下的 lib 目录中。这应该是 Eclipse 安装目录下形如 plugins/org.apache.ant_1.5.3 的子目录。

Python Ant 任务库拷贝完毕之后,必须在 Eclipse 中启用库。选择 Window > Preferences,然后选择 Ant > Runtime。将 Ant Home Entries 展开,其中可看到 Eclipse 使用的库(JAR 文件)列表。选择“ Add JAR”,然后从 Eclipse Ant 插件的 lib 目录中选择 Python Ant JAR 文件,就可以将刚刚拷贝的 Python Ant JAR 文件加入库列表中(请参阅图 8)。


图 8. 向 classpath 中加入 Python Ant 任务
Python Ant tasks added to the classpath 

您现在应该能够创建和运行包含 Python 任务的 Ant 构建脚本了。下面进入构建脚本内部!

创建构建脚本

我将逐步介绍如何创建一个简单的 Python 构建脚本(请参阅清单 1)。完整的构建脚本 build.xml 可从 feedParserTest 项目的顶层目录中找到。


清单 1. 用于编译 Python 源代码的构建脚本片断

<project name="feedParserTest" default="compile">  <taskdef resource="pyAntTasks.properties"/>  <property name="src.dir" value="src"/>  <target name="compile">    <py-compile dir="${src.dir}" pythonpath="${src.dir}" optimize="0"/>  </target></project>

 

先介绍一个只编译 Python 样例代码的构建脚本。<project> 标签总是构建脚本的根标签。<taskdef> 标签声明在整个构建脚本中使用的 Python 任务。在构建脚本的底部,可以定义 compile 目标。目标元素内部是 compile 运行期间执行的任务。特别的是 py-compile 任务,它负责从 src 目录开始,编译所有的 Python 代码。该任务会递归遍历所有的子目录,并编译所有的 Python 模块。脚本中没有采用将 src 目录硬编码到调用之处的方式,而是在构建脚本中定义了称为 src.dir 的属性。然后,在需要使用这个目录名的时候,就可以通过 ${src.dir} 来引用。

要运行构建脚本,可从 Eclipse 中打开它。Eclipse 具有内置的 Ant 构建脚本编辑和浏览功能。Outline 视图可以显示出构建脚本的结构。在 Navigator 视图中,选择该构建脚本,用右键点击,然后选择“Run Ant...”。选择 compile目标,然后点击“Run”。构建脚本执行过程中的输出信息应该显示在 Console 视图中,表示运行成功。

Python 脚本执行任务

接下来将向构建脚本中加入新的目标,用于执行 Python 脚本(请参阅清单 2)。在本例中,可以将 RSS URL 作为参数来执行 feedparser.py 脚本。


清单 2. 运行 feedparser 脚本的构建脚本片断

  <target name="run.feedparser" depends="compile">    <py-run script="src/feedparser/feedparser.py" pythonpath="${src.dir}" optimize="0">      <arg value="http://www.ibm.com/developerworks/news/dw_dwtp.rss">    </py-run>  </target>

 

上面的目标以 RSS URL 为唯一的参数来执行 feedparser.py 脚本。该目标声明为依赖于 compile 目标,所以后者将首先执行。实际上这一步并不是很必要,因为 Python 会根据需要自动编译源代码。如果您执行 run.feedparser目标,就会运行 feedparser.py 脚本,同时将 RSS 的内容输出到 Console 中。

Python 文档任务

Python 的 API 文档编制机制与 Java 技术中的 JavaDoc 系统类似,称为 PyDoc。在构建脚本中加入清单 3 中列出的如下 XML 片断,可为所有的 Python 模块生成 PyDoc。


清单 3. 用于生成 PyDoc 的构建脚本片断

 1:  <property name="pydoc.dir" value="pydoc"/> 2: 3:  <target name="init"> 4:    <mkdir dir="${pydoc.dir}"/> 5:  </target> 6: 7:  <target name="pydoc" depends="init,compile"> 8:    <py-doc pythonpath="${src.dir}" destdir="${pydoc.dir}"> 9:      <fileset dir="${src.dir}">10:        <include name="**/*"/>11:      </fileset>12:    </py-doc>13:  </target>

 

从对上述 pydoc 目标的解析可看出,第 7 行声明了目标名称,并指出它依赖于 init 和 compile 目标。这意味着在运行 pydoc 目标之前,Ant 必须保证 init 和 compile 目标已经运行,如果没有,则首先运行这两个目标。

pydoc 目标所依赖的 init 目标在第 3 至第 5 行定义。 init 目标仅仅创建了一个存放 PyDoc API 文档文件的目录。如前所述,要为所生成文档的保存位置定义一个属性,名为 pydoc.dir。

第 8 行开始是 py-doc 任务。如前所述,您传入生成 pydoc 过程中所使用的 PYTHONPATH 。 destdir 属性告诉 py-doc 任务将生成的 HTML 文档输出到何处。

第 9 至第 11 行定义了在生成文档的过程中应该处理哪些 Python 源文件。文件集是 Ant 脚本中通用的结构,可用于定义所操作的一组文件。这是一种很强大的特性,它使您能够通过名字模式、布尔逻辑和文件属性来选择所要操作的文件。Ant 文档中有这方面的完整描述。本例中递归选择了“src”目录下的所有文件。

Python 单元测试任务

Python 中具有标准的单元测试框架(从 Python 2.3 开始。在 Python 2.2 中这只是可选模块),与 Java jUnit 框架十分类似。测试用例的结构与 jUnit 采用相同的方式。每一个待测试的类和模块通常都具有自己的测试类。测试类中包含测试装置(fixture),它们在 setUp 函数中初始化。每一个测试都编写为测试类中的一个独立的测试函数。unittest 框架会在测试函数之间循环往复,先调用 setUp 、再测试函数、然后清除( tearDown )测试函数。请参阅清单 4 中的样例。


清单 4. Python 单元测试模块
import unittestfrom pprint import pprintimport feedparserclass FeedparserTest(unittest.TestCase):    """    A test class for the feedparser module.    """        def setUp(self):        """        set up data used in the tests.        setUp is called before each test function execution.        """        self.developerWorksUrl = "testData/developerworks.rss"           def testParse09Rss(self):        """        Test a successful run of the parse function for a        0.91 RSS feed.        """        print "FeedparserTest.testParse09RSS()"                result = feedparser.parse(self.developerWorksUrl)        pprint(result)        self.assertEqual(0, result['bozo'])                self.assert_(result is not None)        channel = result['channel']        self.assert_(channel is not None)        chanDesc = channel['description']        self.assertEqual(u'The latest content from IBM developerWorks',            chanDesc)                items = result['items']        self.assert_(items is not None)        self.assert_(len(items)> 3)        firstItem = items[0]        title = firstItem['title']        self.assertEqual(u'Build installation packages with             solution installation and deployment technologies',            title)      def tearDown(self):        """        tear down any data used in tests        tearDown is called after each test function execution.        """        pass                if __name__ == '__main__':    unittest.main()


上述清单是实现 feedparser 模块基本测试功能的测试类。完整的测试类见 feedParserTest 项目下的 src/feedparserTest/FeedparserTest.py。 setUp 函数负责准备整个测试过程中需要使用的测试装置,在本例中只有测试用的 RSS 文件的目录,测试函数将对其进行解析。 testParse09Rss 是真正的测试函数。这个函数调用 feedparser.parse 函数,传递测试用的 RSS 文件,输出解析结果,并通过 TestCase 类的 assert 函数执行基本的检查统作。如果任何 assert 的求值结果不是真,或是在执行过程中抛出任何异常,unittest 就会报告一次测试失败或错误。最后的两行负责在这个测试类内部运行测试,方法是直接运行该模块即可。

要独立运行该测试类,可以按前面所说的相同方式运行 FeedparserTest.py 模块。在 Eclipse Navigator 视图中选择 FeedparserTest.py,然后通过 Python > Run 运行。此时显示启动配置窗口。除 Base 目录之外,其他都保持缺省值即可。Base 目录必须是 feedParserTest 项目的目录,这样才能在当前目录下找到 RSS 文件(testData/developerworks.rss)。修改 base 目录的设置,然后点击“Run”。输出信息显示在 Console 上。

您也许希望我们编写的所有单元测试都能够作为构建的一部分自动执行。将下面清单 5 所示的构建片断加入构建脚本便可实现。


清单 5. 执行单元测试的构建脚本片断
1:  <target name="tests" depends="compile">2:<py-test pythonpath="${src.dir}" dir=".">3:    <fileset dir="${src.dir}">4:<include name="**/*Test.py"/>5:  </fileset>6:  </py-test>7:  </target> 


第一行是目标声明,这与其他的脚本相同。第 2 至第 6 行调用 py-test 任务。这部分代码将在“src”目录下查找所有以“Test.py”结尾的所有文件,并运行所有测试。 PYTHONPATH 设置为“src”,测试执行的当前工作目录就是当前目录(‘.’)。

运行目标的方法是先运行构建脚本,再选择执行“tests”目标。该目标将运行所有以“Test.py”结尾的测试用例,本例中仅有 FeadparserTest.py。


blue_rule.gif
c.gif

c.gif
u_bold.gif
Back to top

 

 

结束语

Eclipse 和 PyDev 插件的结合,以及 Apache Ant 与 Python Ant 任务一起使用,可以为 Python 开发提供完全集成的开发环境和构建/部署工具。这些工具尚在开发过程中,因此要经常查看是否有更新,如果您觉得特别希望看到某种特性,可以卷起袖管自力更生。

Reproduced in: https: //www.cnblogs.com/licheng/archive/2010/07/24/1784257.html

Guess you like

Origin blog.csdn.net/weixin_33998125/article/details/92634272