2016-08-19 39 views
1

我有一個Python 3應用程序應該在某個時候將一個字符串放入剪貼板。我正在使用系統命令echopbcopy,它工作正常。但是,如果字符串包含撇號(並且誰知道,可能還有其他特殊字符),則會退出並顯示錯誤。這是一個代碼示例:在Python3/OS X中,如何將帶撇號的字符串傳遞給終端命令?

import os 

my_text = "Peoples Land" 
os.system("echo '%s' | pbcopy" % my_text) 

它工作正常。但是,如果你糾正字符串「民地」,它返回此錯誤:

sh: -c: line 0: unexpected EOF while looking for matching `'' 
sh: -c: line 1: syntax error: unexpected end of file 

我想我需要把它傳遞給shell命令之前的字符串以某種方式進行編碼,但我還是不知道怎麼辦。什麼是完成這個最好的方法?

回答

1

對於字符串撇號:

  • 您可以使用'%r'代替'%s'
  • my_text = "People's Land" 
    os.system("echo '%r' | pbcopy" % my_text) 
    

要得到字符串的殼逸出版本:

  • 您可以使用shlex.quote()

    import os, shlex 
    my_text = "People's Land, \"xyz\", hello" 
    os.system("echo %s | pbcopy" % shlex.quote(my_text)) 
    
+0

我試圖在我的代碼中實現這個建議,但我很難找出爲什麼它失敗了。我發現,當使用'shlex.quote()'時,我仍然必須刪除單引號。現在它工作正常;) –

1

這實際上與shell逃脫有更多關係。

在命令行試試這個:

echo 'People's Land' 

echo 'People'\''s Land'

在Python中這樣的事情應該工作:

>>> import os 
>>> my_text = "People'\\''s Land" 
>>> os.system("echo '%s' > lol" % my_text) 
+0

是否有一個python函數可以做這種轉義?我正在處理輸入到數據庫中的值,因此最好讓代碼執行該轉換。 –

+0

https://docs.python.org/3.5/library/shlex.html – Vatsal

相關問題