【问题标题】:Python will run in Unix, not Windows. How can you run an external python command in terminal?Python 将在 Unix 上运行,而不是 Windows。如何在终端中运行外部 python 命令?
【发布时间】:2014-02-23 00:46:03
【问题描述】:

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

【问题讨论】:

  • 你可能需要启动调试器
  • 你没有逃避url,所以这可能会导致各种麻烦。将参数作为列表传递,例如:['python', 'script', url] 以使 Popen 为您进行转义。 python 二进制文件也可能不在您的%PATH% 中,因此请尝试使用完整路径(即C:/python33/python.exe),或设置%PATH%

标签: python windows shell ipython windows-shell


【解决方案1】:

使用

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

最好将os.abspath("GetAlexRanking.py") 作为参数传递。

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

可在 Windows、Linux、Mac 上使用。

【讨论】:

    猜你喜欢
    • 2014-05-27
    • 2017-09-04
    • 1970-01-01
    • 2020-03-02
    • 2017-07-06
    • 2018-12-28
    • 2018-09-01
    • 2018-10-24
    • 2015-06-13
    相关资源
    最近更新 更多