2012年9月28日金曜日

Introducing the os Modules

Introducing the os Modules

Tools in the os Modules

Table 2-1. Commonly used os module tools
Tasks Tools
Shell variables os.environ
Running programs os.system, os.popen, os.execv, os.spawnv
Spawning processes os.fork, os.pipe, os.waitpid, os.kill
Descriptor files, locks os.open, os.read, os.write
File processing os.remove, os.rename, os.mkfifo, os.mkdir, os.rmdir
Administrative tools os.getcwd, os.chdir, os.chmod, os.getpid, os.listdir, os.access
Portability tools os.sep, os.pathsep, os.curdir, os.path.split, os.path.join
Pathname tools os.path.exists('path'), os.path.isdir('path'), os.path.getsize('path')

 

Administrative Tools

>>> os.getpid()
7980
>>> os.getcwd()
'C:\\PP4thEd\\Examples\\PP4E\\System'

>>> os.chdir(r'C:\Users')
>>> os.getcwd()
'C:\\Users'

 

Portability Constants

>>> os.pathsep, os.sep, os.pardir, os.curdir, os.linesep
(';', '\\', '..', '.', '\r\n')

 

Common os.path Tools

>>> os.path.isdir(r'C:\Users'), os.path.isfile(r'C:\Users')
(True, False)
>>> os.path.isdir(r'C:\config.sys'), os.path.isfile(r'C:\config.sys')
(False, True)
>>> os.path.isdir('nonesuch'), os.path.isfile('nonesuch')
(False, False)

>>> os.path.exists(r'c:\Users\Brian')
False
>>> os.path.exists(r'c:\Users\Default')
True
>>> os.path.getsize(r'C:\autoexec.bat')
24
 
>>> os.path.split(r'C:\temp\data.txt')
('C:\\temp', 'data.txt')

>>> os.path.join(r'C:\temp', 'output.txt')
'C:\\temp\\output.txt'

>>> name = r'C:\temp\data.txt'                            # Windows paths
>>> os.path.dirname(name), os.path.basename(name)
('C:\\temp', 'data.txt')

>>> name = '/home/lutz/temp/data.txt'                     # Unix-style paths
>>> os.path.dirname(name), os.path.basename(name)
('/home/lutz/temp', 'data.txt')

>>> os.path.splitext(r'C:\PP4thEd\Examples\PP4E\PyDemos.pyw')
('C:\\PP4thEd\\Examples\\PP4E\\PyDemos', '.pyw') 

 

Running Shell Commands from Script

Other os module Exports

0 件のコメント:

コメントを投稿