星期一, 8月 25, 2008

[Python]subprocess

http://fannys23.pixnet.net/blog/post/15367167

http://mrwlwan.wordpress.com/2008/10/15/python%EF%BC%9A%E4%BD%BF%E7%94%A8-subprocess-%E8%B0%83%E7%94%A8%E5%A4%96%E9%83%A8%E5%91%BD%E4%BB%A4/

這邊有簡短的使用說明,根據我個人使用的經驗,
shell = True是執行shell的指令
shell = False是執行自己的程式
還有最好用
cmd = 'cat /a/b/c'
subprocess.call(cmd.split(), shell = True)

記得要用cmd.split()
我一開始就是忘記用.....>_< Update: 經過反覆的測試,發現我之前講錯了.....>_< shell = False 表示輸入需為sequence也就是list,然後不可以有特殊字元,例如regular expression,因為當shell = False 是用os.execvp()去執行child program,而regular expression是shell提供的功能,所以當shell = False,就沒有shell的功能,只能要執行什麼就執行什麼 例如: #!/usr/bin/env python import subprocess cmd = 'cat /etc/passwd' subprocess.call(cmd.split(), shell = False) 就會得到passwd的所有資料 但不能用cmd = 'cat /etc/*' 當shell = False會以為你要找的是 * 這個檔案 shell = True 如果input是string的話,表示把input丟到shell去執行,可以有regular expression也可以有分號 例如: #!/usr/bin/env python import subprocess cmd = 'cat /etc/*' subprocess.call(cmd, shell = True) 就會cat所有在etc下面的檔案內容 反正只要在shell下可以執行的,都可以寫在這 cmd = 'cat /etc/passwd | grep root' cmd = 'ls /etc/; ps axu' 如果input是sequence的話,我看不太懂....>_<
原文在這:
On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments.

看有沒有高手解釋一下~~~~^^

另外可以用subprocess.Popen()
用subprocess.call()只有return code
用subprocess.Popen()則是可以接回執行結果
例如:
#!/usr/bin/env python
import subprocess
cmd = 'cat /etc/*'
result = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE)
(stdout, stderr) = result.communicate()
這個時候result是一個pipe
這時候就可以抓你要的執行結果

千萬注意一點,就是close_fds的設定
If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr.
另外
* Popen raises an exception if the execution fails.
* the capturestderr argument is replaced with the stderr argument.
* stdin=PIPE and stdout=PIPE must be specified.
* popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen.

表示說原則上,你需要在Unix上面設定close_fds=TRUE,但在windows上設定close_fds=TRUE就不能redirect standard handle by setting stdin, stdout, stderr.

沒有留言:

張貼留言