在google上搜了一下,发现在Python 里调用系统命令的方法有N种。
1. 使用os.popen
>>> import os
>>> pipe=os.popen("df -lh").read()
>>> print pipe
/dev/sda6 2.0G 333M 1.6G 18% /
/dev/sda1 99M 16M 79M 17% /boot
tmpfs 948M 0 948M 0% /dev/shm
/dev/sda7 115G 96G 14G 88% /home
/dev/sda2 7.8G 3.3G 4.2G 45% /usr
/dev/sda5 3.9G 302M 3.4G 9% /va
这种方式可以将返回结果赋给一个变量,可以在程序中处理这些结果。 这种方法比较方便。
2. 使用os.system()
>>> import os
>>> os.system('df -lh')
/dev/sda6 2.0G 333M 1.6G 18% /
/dev/sda1 99M 16M 79M 17% /boot
tmpfs 948M 0 948M 0% /dev/shm
/dev/sda7 115G 96G 14G 88% /home
/dev/sda2 7.8G 3.3G 4.2G 45% /usr
/dev/sda5 3.9G 302M 3.4G 9% /var
这个命令仅在终端执行命令。
3. 使用 subprocess.call()
>>> import subprocess
>>> subprocess.call(['df','-lh'])
/dev/sda6 2.0G 333M 1.6G 18% /
/dev/sda1 99M 16M 79M 17% /boot
tmpfs 948M 0 948M 0% /dev/shm
/dev/sda7 115G 96G 14G 88% /home
/dev/sda2 7.8G 3.3G 4.2G 45% /usr
/dev/sda5 3.9G 302M 3.4G 9% /var
0
>>>
subprocess.call(*popenargs, **kwargs)
Run command with arguments. Wait for command to complete, then return the returncode attribute.
4. 使用subprocess.Popen(command, shell=True)
帮助文档对该方法说明:
class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
Arguments are:
args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or the string if a string is given, but can be explicitly set by using the executable argument. When executable is given, the first item in the args sequence is still treated by most programs as the command name, which can then be different from the actual executable name. On Unix, it becomes the display name for the executing program in utilities such as ps.
On Unix, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. If a string is specified for args, it will be used as the name or path of the program to execute; this will only work if the program is being given no arguments.
>>> import subprocess
>>> cmd='df -lh'
>>> subprocess.Popen(cmd,shell=True)
<subprocess.Popen object at 0xb7eab26c>
/dev/sda6 2.0G 333M 1.6G 18% /
/dev/sda1 99M 16M 79M 17% /boot
tmpfs 948M 0 948M 0% /dev/shm
/dev/sda7 115G 96G 14G 88% /home
/dev/sda2 7.8G 3.3G 4.2G 45% /usr
/dev/sda5 3.9G 302M 3.4G 9% /var
关于这些命令的具体说明,可以参考联机文档。
------------------------------------------------------------------------------
Blog: http://blog.csdn.net/tianlesoftware
网上资源: http://tianlesoftware.download.csdn.net
相关视频:http://blog.csdn.net/tianlesoftware/archive/2009/11/27/4886500.aspx
DBA1 群:62697716(满); DBA2 群:62697977(满)
DBA3 群:62697850 DBA 超级群:63306533;
聊天 群:40132017
--加群需要在备注说明Oracle表空间和数据文件的关系,否则拒绝申请