``system`` 函数在当前进程下执行一个新命令, 并等待它完成, 如 [Example 1-34 #eg-1-34] 所示.
====Example 1-34. 使用 os 执行操作系统命令====[eg-1-34]
```
File: os-example-8.py
import os
if os.name == "nt":
command = "dir"
else:
command = "ls -l"
os.system(command)
*B*-rwxrw-r-- 1 effbot effbot 76 Oct 9 14:17 README
-rwxrw-r-- 1 effbot effbot 1727 Oct 7 19:00 SimpleAsyncHTTP.py
-rwxrw-r-- 1 effbot effbot 314 Oct 7 20:29 aifc-example-1.py
-rwxrw-r-- 1 effbot effbot 259 Oct 7 20:38 anydbm-example-1.py
...*b*
```
命令通过操作系统的标准 shell 执行, 并返回 shell 的退出状态. 需要注意的是在 Windows 95/98
下, shell 通常是 ``command.com`` , 它的推出状态总是 0.
由于 11os.system11 直接将命令传递给 shell , 所以如果你不检查传入参数的时候会很危险
(比如命令 ``os.system("viewer %s" % file)``, 将 file 变量设置为
"``sample.jpg; rm -rf $HOME" ....``). 如果不确定参数的安全性, 那么最好使用
``exec`` 或 ``spawn`` 代替(稍后介绍).
====Example 1-34. 使用 os 执行操作系统命令====[eg-1-34]
```
File: os-example-8.py
import os
if os.name == "nt":
command = "dir"
else:
command = "ls -l"
os.system(command)
*B*-rwxrw-r-- 1 effbot effbot 76 Oct 9 14:17 README
-rwxrw-r-- 1 effbot effbot 1727 Oct 7 19:00 SimpleAsyncHTTP.py
-rwxrw-r-- 1 effbot effbot 314 Oct 7 20:29 aifc-example-1.py
-rwxrw-r-- 1 effbot effbot 259 Oct 7 20:38 anydbm-example-1.py
...*b*
```
命令通过操作系统的标准 shell 执行, 并返回 shell 的退出状态. 需要注意的是在 Windows 95/98
下, shell 通常是 ``command.com`` , 它的推出状态总是 0.
由于 11os.system11 直接将命令传递给 shell , 所以如果你不检查传入参数的时候会很危险
(比如命令 ``os.system("viewer %s" % file)``, 将 file 变量设置为
"``sample.jpg; rm -rf $HOME" ....``). 如果不确定参数的安全性, 那么最好使用
``exec`` 或 ``spawn`` 代替(稍后介绍).