
Most operating systems provide a command-line interface, also known as a shell. Shells usually provide commands to navigate the file system and launch applications. For example, in Unix, you can change directories with cd, display the contents of a directory with ls, and launch a web browser by typing (for example) firefox.
Any program that you can launch from the shell can also be launched from Python using a pipe. A pipe is an object that represents a running process. For example, the Unix command 1 ls -l normally displays the contents of the current directory (in long format). You can launch ls with os.popen:
>>> cmd = 'ls -l'>>> fp = os.popen(cmd)
The argument is a string that contains a shell command. The return value is a file pointer that behaves just like an open file. You can read the output from the ls process one line at a time with readline or get the whole thing at once with read:
>>> res = fp.read()
When you are done, you close the pipe like a file:
>>> stat = fp.close()>>> print statNone
The return value is the final status of the ls process; None means that it ended normally (with no errors).
- 瀏覽次數:1582