2012-04-13 68 views
1

我有一個原子模擬程序(用Fortran編寫,我沒有源代碼)提示用戶輸入一個溫度,每個原子的迭代次數的質量等然後運行給定輸入文件的模擬(指定所有原子的初始位置)。在所有迭代之後,程序輸出一個帶有原子最終位置的文本文件,然後關閉。如何從Python運行命令行程序

我試圖在不同的溫度下運行相同的模擬,所以我希望通過Python自動化輸入過程。因此,Python程序將:

  1. 打開模擬程序(「sim.exe」)
  2. 輸入溫度,質量,迭代等進入命令行自動
  3. 輸出文件將是生成並複製到另一個不同名稱的文件中,以免它被覆蓋。
  4. 回到數字1,在不同的溫度,但相同的質量,迭代等

我的主要問題是數2.我不能找出如何輸入到命令行程序來自Python。它甚至有可能嗎?我已經讀過它與os或subprocess模塊​​有關,但我不清楚它們是如何工作的。

注意:我使用Windows。

回答

4
import sys 
import subprocess 

theproc = subprocess.Popen([sys.executable, "myCMDscript"]) 
theproc.communicate() 
+0

爲什麼'SYS。 executable'? – 2012-04-13 19:54:49

+0

sys.executable可以運行自己的另一個實例或找到我想的配置數據。 – 2012-04-13 20:01:22

+1

OP提到這個子進程被稱爲'sim.exe' - 幾乎看起來像一個Python腳本的名字。 – 2012-04-13 20:16:15

7

如果你能盲目輸入您的數據,而無需等待具體的提示,這個問題應該很容易解決:

import os 
import shutil 
import subprocess 
import time 

proc = subprocess.Popen(["sim.exe"], stdin=subprocess.PIPE) 
while True: 
    proc.communicate(input="line1\nline2\nline3\n") 
    while not os.path.exists(outputfilepath): 
     time.sleep(1) 
    shutil.move(outputfilepath, uniq_outputfilepath) 

當然,這將是更安全掃描程序的輸出和錯誤的預期和意想不到的模式,以進行或中止。這將有可能通過POPEN()的輸出和錯誤ARGS也設置爲subprocess.PIPE並調用這樣的溝通:

stdout, stderr = proc.communicate(input="line1\nline2\nline3\n") 

檢查communicate() documentation瞭解詳情。

如果使用Python3中,輸入字符串必須轉換爲字節串,以防止提高溝通「類型錯誤:‘STR’不支持緩衝區接口」

proc.communicate(input=bytes("line1\nline2\nline3\n", "UTF-8")) 
+0

謝謝!然而,我總是收到一條錯誤消息:TypeError:'str'不支持緩衝區接口 – teskata 2012-04-13 20:38:25

+0

噢,這聽起來像Python3。像'proc.communicate(input = bytes(「line1 \ nline2 \ nline3 \ n」,「UTF-8」))或'proc.communicate(input =「line1 \ nline2 \ nline3 \ n」.encode 「utf-8」))的工作? – 2012-04-13 20:49:45

+0

剛剛測試過。 bytes()調用獲勝。將爲我的答案添加一個Python3筆記。 – 2012-04-13 20:58:24