2012-07-24 75 views
0

我試圖從Python中稱之爲「的sed」和有麻煩經由任一subprocess.check_call通過命令行()或使用os.system() 。傳遞外殼命令與Python使用os.system()或subprocess.check_call()

我在Windows 7中,但使用從Cygwin的(它的路徑)「的sed」。

如果我這樣做從Cygwin的外殼,它工作正常:

$ sed 's/&amp;nbsp;/\&nbsp;/g' <"C:foobar" >"C:foobar.temp" 

在Python中,我已經得到了完整路徑,我在「名稱」工作。我想:

command = r"sed 's/&amp;nbsp;/\&nbsp;/g' " + "<" '\"' + name + '\" >' '\"' + name + '.temp' + '\"' 
subprocess.check_call(command, shell=True) 

所有級聯是有,以確保我身邊的輸入和輸出文件名雙引號(如果有在Windows文件路徑空格)。

我也嘗試過用替換最後一行:

os.system(command) 

無論哪種方式,我得到這個錯誤:

sed: -e expression #1, char 2: unterminated `s' command 
'amp' is not recognized as an internal or external command, 
operable program or batch file. 
'nbsp' is not recognized as an internal or external command, 
operable program or batch file. 

然而,正如我所說,它的工作原理確定從控制檯。我究竟做錯了什麼?

+5

我可以建議您完全跳過sed,並將其作爲四行Python腳本編寫嗎? – 2012-07-24 01:49:46

+0

你不能在迭代器中使用像'<' or '>'這樣的shell結構,因爲'check_call'只是引用它們。你必須把它們組合成一個字符串......但是聽奈德......他知道他的東西。 – 2012-07-24 01:53:34

回答

1

我同意斯內德爾德的assessment,但覺得你可能要考慮使用下面的代碼是什麼,因爲它可能做什麼,你最終要完成的任務,可以輕鬆地與Python的fileinput模塊的幫助下完成的:

import fileinput 

f = fileinput.input('C:foobar', inplace=1) 
for line in f: 
    line = line.replace('&amp;nbsp;', '&nbsp;') 
    print line, 
f.close() 
print 'done' 

這將在地方給定的文件有效更新爲使用的關鍵字建議。還有一個可選的backup=關鍵字 - 以上未使用 - 如果需要,它將保存原始文件的副本。

BTW,謹慎的有關使用諸如C:foobar東西指定文件名的詞,因爲在Windows這意味着名字無論當前目錄是驅動器C :,你想要什麼這可能不是一個文件。

+0

謝謝;那只是一個例子。文件路徑來自os.walk;我正在嘗試處理一個完整的文件(數百個文件)。 – 2012-07-24 15:57:48

+0

@ nerdfever.com:那麼,如果你使用'os.walk'來收集文件名來處理它,那麼在Python中處理每一個文件名就更有意義了 - 這可能會更快一些和使用外部程序一樣容易。 – martineau 2012-07-24 18:48:14

5

由子使用的外殼可能不是你想要的外殼。您可以使用executable='path/to/executable'指定外殼。不同的殼有不同的引用規則。

更妙可能跳過subprocess乾脆,並寫爲純Python:

with open("c:foobar") as f_in: 
    with open("c:foobar.temp", "w") as f_out: 
     for line in f_in: 
      f_out.write(line.replace('&amp;nbsp;', '&nbsp;')) 
1

我想你會發現,在Windows的Python,它實際上不是使用的cygwin外殼運行你的命令,而是使用cmd.exe

而且,cmd並不單引號發揮好辦法bash一樣。

你只要做到以下幾點,以確認:

c:\pax> echo hello >hello.txt 

c:\pax> type "hello.txt" 
hello 

c:\pax> type 'hello.txt' 
The system cannot find the file specified. 

我認爲最好的辦法是使用Python本身來處理文件。 Python語言是一種跨平臺的語言,旨在消除所有這些平臺特定的不一致情況,例如您剛發現的那種。