Python之firstscript

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1A first script

1)script1.py

- imports a Python module (libraries of additional tools) to fetch the name of the platform

- calls threePRint function to display the script’s results

- uses a variable named x, created when it’s assigned, to hold onto a string object

1#A first Python script2importsys#Load a library module3print(sys.platform)4print(2 ** 10)#Raise 2 to a power5x ='Spam!'6print(x * 8)#String repetition

2)Run

$pythonscript1.pylinux21024

Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

2Module Imports and Reloads

1)Module

Modules are simply text files containing Python statements. Python executes all the code in a module file from top to bottom each time we run the file. Each file is a module, and modules import other modules to use the names they define. Modules are processed with two statements and one important function:

import - Lets a client (importer) fetch a module as a whole

from- Allows clients to fetch particular names from a module

imp.reload- Provides a way to reload a module’s code without stopping Python

2)Import

Every file of Python source code whose name ends in a .py extension is a module.Other files canaccessthe items a module defines by importing that module; importOperations essentially load another file and grant access to that file’s contents.

$ pythonPython2.7.3 (default, Dec 18 2014, 19:10:20)

[GCC 4.6.3] on linux2

Type "help", "copyright", "credits" or "license" for more information.>>>importscript1linux21024

Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

This works, but only once persession(really, process) by default. After the first import, later imports do nothing, even if you change and save the module’s source file again in another window.

This is by design; imports are too expensive an operation to repeat more than once per file, per program run. Imports must find files, compile them to byte code, and run the code.

3)Reload

If want to force Python to run the file again in the same session without stopping and restarting the session, we need to instead call thereloadfunction available in theimpstandard library module (this function is also a simple built-in in Python 2.6, but not in 3.0).

>>>fromimpimportreload>>>reload(script1)linux21024

Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

<module 'script1' from 'script1.pyc'>

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航