2010-04-05 177 views
1

我需要一種方法從外部編輯器獲取數據。從外部程序獲取數據

def _get_content(): 
    from subprocess import call 
    file = open(file, "w").write(some_name) 
    call(editor + " " + file, shell=True) 
    file.close() 
    file = open(file) 
    x = file.readlines() 

    [snip] 

我個人認爲應該有更優雅的方式。你看,我需要與外部編輯器交互並獲取數據。

你知道更好的方法/有更好的想法嗎?

編輯:

馬塞洛給我帶來了使用上的tempfile這樣做的想法。

這裏是我如何做到這一點:

def _tempfile_write(input): 
    from tempfile import NamedTemporaryFile 

    x = NamedTemporaryFile() 
    x.file.write(input) 
    x.close() 
    y = open(x) 

    [snip] 

這做工作,但也不太令人滿意。 聽說有關產卵的東西嗎?

+1

你的問題是相當模糊。你究竟想要達到什麼目的?你覺得這種方法有什麼不好的地方?是「我需要用戶輸入一些文本並將該文本作爲字符串」?是「我需要用戶編輯一個預先存在的文件」?你在問如何產生一個新的編輯器進程或如何從用戶那裏獲得輸入? – RarrRarrRarr 2010-04-05 05:34:41

+0

我正在討論來自用戶的輸入。 :)我承認醜陋不是正確的詞......也許是說,我正在尋找一個更優雅的方式來做這件事(如果有的話)。 – 2010-04-05 22:05:20

回答

2

我推薦使用的列表,而不是一個字符串:

def _get_content(editor, initial=""): 
    from subprocess import call 
    from tempfile import NamedTemporaryFile 

    # Create the initial temporary file. 
    with NamedTemporaryFile(delete=False) as tf: 
     tfName = tf.name 
     tf.write(initial) 

    # Fire up the editor. 
    if call([editor, tfName]) != 0: 
     return None # Editor died or was killed. 

    # Get the modified content. 
    with open(tfName).readlines() as result: 
     os.remove(tfName) 
     return result 
+0

謝謝邁克。這是個好主意。 – 2010-04-06 21:25:28

+1

Gah,忘記了理由:你想使用一個列表來調用''和'shell = False',因爲這樣你就不必擔心轉義文件名中的任何字符(空格,'&', ';'等)殼賦予特殊的含義。當然,NamedTemporaryFile不應該爲這些字符提供一個文件名,但是這是一個很好的習慣。 – 2010-04-06 21:59:53

+0

謝謝你的提示! – 2010-04-08 00:53:58

3

這是所有程序都這麼做的方式,AFAIK。當然,我使用的所有版本控制系統都會創建一個臨時文件,並將其傳遞給編輯器,並在編輯器退出時檢索結果,就像您一樣。

+0

提到臨時文件是好的..我在那個名爲'tempfile'上找到了一個好的Python模塊。我認爲這聽起來很棒。 – 2010-04-05 22:06:58

1

編輯器只是讓你交互地編輯一個文件。你也可以用Python編輯文件。沒有必要調用外部編輯器。

for line in open("file"): 
    print "editing line ", line 
    # eg replace strings 
    line = line.replace("somestring","somenewstring") 
    print line 
+0

是的,我知道。雖然我需要獲得用戶輸入,然後立即處理這些數據,然後將其全部存儲在數據庫中,否則我會這樣做。 :) – 2010-04-05 22:15:25