Python将在Unix中运行,而不是在Windows中运行。如何在终端中运行外部python命令?

时间:2014-02-23 00:46:03

标签: python windows shell ipython windows-shell

我正在尝试在iPython中运行一些代码

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终端运行时也能正常运行。

1 个答案:

答案 0 :(得分:1)

使用

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

并且更好地传递os.abspath("GetAlexRanking.py")作为参数。

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

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

相关问题