Professional Documents
Culture Documents
Head First
Head First
The first window, the Python Shell, is a REPL environment used to run
snippets of Python code, typically a single statement at a time.
Remember: the
interpreter starts
at the top of the
file and works down
toward the bottom,
executing each line
of Python code as
it goes.
------------------------------
Python’s standard library is very rich, and provides a lot of reusable code.
Let’s look at another module, called os, which provides a platform-independent way
to interact with your underlying operating system.
where_am_I = getcwd()
# ...then invoke as
required
The standard library is the jewel in Python’s crown, supplying reusable modules
that help you with
everything from, for example, working with data, through manipulating ZIP archives,
to sending emails,
to working with HTML. The standard library even includes a web server, as well as
the popular SQLite
database technology.
The sys
module exists to help you learn more about your interpreter’s system. Here’s how to
determine the identity
of your underlying operating system, by first importing the sys module, then
accessing the platform
attribute:
The sys module is a good example of a reusable module that primarily provides
access to preset attributes
(such as platform). As another example, here’s how to determine which version of
Python is running,
which we pass to the print function to display on screen:
>>> print(sys.version)
>>> import os
>>> os.getcwd()
'/Users/HeadFirst/CodeExamples'
You can access your system’s environment variables, as a whole (using the environ
attribute) or
individually (using the getenv function):
>>> os.environ
'environ({'XPC_FLAGS': '0x0', 'HOME': '/Users/HeadFirst', 'TMPDIR': '/var/
folders/18/t93gmhc546b7b2cngfhz10l00000gn/T/', ... 'PYTHONPATH': '/Applications/
Python 3.4/IDLE.app/Contents/Resources', ... 'SHELL': '/bin/bash', 'USER':
'HeadFirst'})'
#The “environ”
attribute
contains lots
of data.
>>> os.getenv('HOME')
'/Users/HeadFirst'
datetime module
invoke the date.isoformat function and pass in today’s date to display a much more
userfriendly
version of today’s date, which is converted to a string by isoformat:
>>> datetime.date.isoformat(datetime.date.today())
'2015-05-31'
# todays date as a string.
what time it
is?
importing the time module, call the strftime function and specify how you want the
time
displayed. In this case, we are interested in the current time’s hours (%H) and
minutes (%M) values in 24-hour
format:
>>> import time
>>> time.strftime("%H:%M")
'23:55'
How about working out the day of the week, and whether or not it’s before noon?
Using the %A %p
specification with strftime does just that:
>>> time.strftime("%A %p")
'Sunday PM'
pg 13