CHAPTER 3
Script Execution Context
“I’d Like to Have an Argument, Please”
Python scripts don’t run in a vacuum (despite what you may have heard). Depending
on platforms and startup procedures, Python programs may have all sorts of enclosing
context—information automatically passed in to the program by the operating system
when the program starts up. For instance, scripts have access to the following sorts of
system-level inputs and interfaces:
Current working directory
os.getcwd g i v e s a c c e s s t o t h e d i r e c t o r y f r o m w h i c h a s c r i p t i s s t a r t e d , a n d m a n y f i l e
tools use its value implicitly.
Command-line arguments
sys.argv gives access to words typed on the command line that are used to start
the program and that serve as script inputs.
Shell variables
os.environ provides an interface to names assigned in the enclosing shell (or a
parent program) and passed in to the script.
Standard streams
sys.stdin, stdout, and stderr e x p o r t t h e t h r e e i n p u t / o u t p u t s t r e a m s t h a t a r e a t t h e
heart of command-line shell tools, and can be leveraged by scripts with print op-
tions, the os.popen call and subprocess module introduced in Chapter 2, the
io.StringIO class, and more.
Such tools can serve as inputs to scripts, configuration parameters, and so on. In this
chapter, we will explore all these four context’s tools—both their Python interfaces
and their typical roles.
103
Do
wnload from Wow! eBook <www.wowebook.com>