I am trying to run some code in iPython which

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.

My code runs in a Unix environment, but I cannot make it run using iPython and Windows. The external function that I call will also work when called in a windows terminal, but not when called, as below, in an iPython notebook. What have I done wrong? What else can I try?

Here is my code :

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

How can I make this code run using iPython in Windows? It currently gives no error but the cmd_out variable always prints "None" rather than a correct value - the python command isn't being run correctly (however it will work in a normal Python/Unix environment).

Edit: Also runs correctly when ran from Windows terminal.

有帮助吗?

解决方案

use

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

and better pass os.abspath("GetAlexRanking.py") as argument.

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

can be used on Windows, Linux, Mac.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top