1. 程式人生 > >python呼叫外部程式

python呼叫外部程式

轉載地址:  https://www.cnblogs.com/songwenlong/p/5940155.html

a.os.system方法

Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

On Unix, the return value is the exit status of the process encoded in the format specified for 

wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variableCOMSPEC

: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the 

Replacing Older Functions with the subprocess Module section in the subprocessdocumentation for some helpful recipes.

Availability: Unix, Windows.

os模組中的system()函式可以方便地執行其他程式或者指令碼。其函式原型為:
os.system(command)
command 為要執行的命令,近似於Windows下cmd視窗中輸入的命令。

如果要向程式或者指令碼傳遞引數,可以使用空格分隔程式及多個引數。

b.用subprocess.call()代替os.system()

17.1.4.3. Replacing 

1 status = os.system("mycmd" + " myarg")
2 # becomes
3 status = subprocess.call("mycmd" + " myarg", shell=True)

Notes:

  • Calling the program through the shell is usually not required.

A more realistic example would look like this:

複製程式碼
1 try:
2     retcode = call("mycmd" + " myarg", shell=True)
3     if retcode < 0:
4         print >>sys.stderr, "Child was terminated by signal", -retcode
5     else:
6         print >>sys.stderr, "Child returned", retcode
7 except OSError as e:
8     print >>sys.stderr, "Execution failed:", e
複製程式碼

 例項演示:

開啟記事本:

1 import os
2 os.system('notepad')

1 import subprocess
2 subprocess.call('notepad')

我們看以下程式碼:

1 import os
2 os.system(r'"D:\Program Files (x86)\Netease\CloudMusic\cloudmusic.exe"')

這段程式碼會啟動網易雲音樂,效果和我們在cmd視窗中輸入 "D:\Program Files (x86)\Netease\CloudMusic\cloudmusic.exe" 效果一樣。注意字串中含有空格,所以有 r''

而以下程式碼也可以實現同樣的功能:

1 import subprocess
2 subprocess.call("D:\Program Files (x86)\Netease\CloudMusic\cloudmusic.exe")

同上面那段程式碼的區別只是括號中的 r''

到目前為止一切正常,我們再看下面的程式碼,嘗試著同時開啟兩個程式:

1 import os
2 os.system(r'"D:\Program Files (x86)\Netease\CloudMusic\cloudmusic.exe""notepad"')
3 4 os.system("D:\Program Files (x86)\Netease\CloudMusic\cloudmusic.exe""notepad")
5 6 os.system(""D:\Program Files (x86)\Netease\CloudMusic\cloudmusic.exe""notepad"")

以上嘗試都不會成功。

換做subprocess.call()函式也不能實現。

os.system()和subprocess.call()的區別以後補充。