2011-12-05 14 views
5

我在使用os.system命令正確轉義從Python內部對shell的調用時遇到了問題。我試圖做的相當於:正確處理shell使用os.system從Python轉義

$ cat test | sort --stable -t $'\t' -k1,1 

從Python內部,將它傳遞給shell。

我想:

import os 
cmd = "cat %s | sort --stable -t $'\\t' -k1,1" %("test") 
os.system(cmd) 

,但我得到的錯誤:

sort: multi-character tab `$\\t' 

雖然它從殼正常工作。我試圖通過在Python中添加額外的斜槓來逃避\t,但我必須缺少其他的東西。任何想法如何解決這個問題?

感謝。

+0

可以傳遞文件名作爲arg進行排序,並跳過'cat file |'。祝你好運。 – shellter

回答

5

os.system不像您所期望的那樣在正常的bash環境中執行命令。你可以解決它通過簡單地調用來砸自己:

import os 
cmd = """/bin/bash -c "cat %s | sort --stable -t $'\t' -k1,1" """ % "test" 
os.system(cmd) 

但是你應該知道,os.system已被標記爲過時,將在Python的未來版本中被刪除。您可以面向未來的代碼使用subprocess的簡便方法call模仿os.system的行爲:

import subprocess 
cmd = """/bin/bash -c "cat %s | sort --stable -t $'\t' -k1,1" """ % "test" 
subprocess.call(cmd, shell=True) 

有更多的方式,以與如果你有興趣的子模塊,電話:

http://docs.python.org/library/subprocess.html#module-subprocess

1

首先,你應該避免無用的貓:http://google.com/search?q=uuoc

其次,你確定你的排序命令不理解反斜槓?這應該工作:

sort --stable -t'\t' -k1,1 test 

還應該從Python的工作只是罰款:

os.system("sort --stable -t'\\t' -k1,1 test") 
# or 
os.system(r"sort --stable -t'\t' -k1,1 test") 

最後,如果切換到subprocess(推薦),避免使用shell=True

subprocess.call(["sort", "--stable", "-t\t", "-k1,1", "test"]) 
相關問題