2014-02-23 61 views
0

我試圖運行IPython的一些代碼,Python將在Unix中運行,而不是Windows。你怎麼能在終端中運行一個外部python命令?

will read in a tsv as a list, 
go through it row-by row, 
    run an external python command on each line, 
    save the output into a list 
append this to our tsv at the end. 

我的代碼在Unix環境中運行,但我不能使其運行使用IPython的和Windows。我調用的外部函數在windows終端中調用時也可以工作,但不會在iPython筆記本中調用,如下所示。我做錯了什麼?我還能嘗試什麼?

這裏是我的代碼:

import csv 
import GetAlexRanking #External Method exposed here 
import subprocess 
import pandas as p 
loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter=' ') 
with open('list.tsv','rb') as tsvin, open('output.csv', 'wb') as csvout: 
    tsvin = csv.reader(tsvin, delimiter='\t') 
    csvout = csv.writer(csvout) 

    for row in tsvin: 
     count = 0 
     url = str([row[count]]) 
     cmd = subprocess.Popen("python GetAlexRanking.py " + url ,shell=True) 
     cmd_out, cmd_err = cmd.communicate() 
     cmd_string = str(cmd_out) 
     print ">>>>>>>URL : " + url + " " + cmd_string #testing 
     csvout.writerows(url + "\t" + cmd_string) #writing 
     count+=1 

我怎樣才能讓在Windows中使用IPython的這個代碼運行?它目前沒有錯誤,但是cmd_out變量總是輸出「None」而不是正確的值 - python命令沒有正確運行(但是它可以在普通的Python/Unix環境中運行)。

編輯:從Windows終端運行時也能正確運行。

+0

您可能需要啓動調試器 – sureshvv

+1

您不會轉義'url',這樣可能會導致各種麻煩。將參數傳遞爲如下列表:'['python','script',url]'讓'Popen'爲你逃跑。 'python'二進制文件也可能不在你的'%PATH%'中,因此請嘗試使用完整路徑(即'C:/ python33/python.exe')或設置'%PATH%'。 – Carpetsmoker

回答

1

使用

subprocess.Popen([sys.executable, "GetAlexRanking.py", url]) 

和更好的通os.abspath("GetAlexRanking.py")作爲參數。

>>> sys.executable 
'C:\\Python27\\pythonw.exe' 

可以在Windows,Linux,Mac上使用。