为什么在Windows 3上使用Python 3 IDLE而不在Ubuntu上的终端中?

时间:2011-12-07 09:42:31

标签: python ubuntu io python-idle

我有一个程序,我使用input()从STDIN获取输入。

我使用输入读取一行中的第一个单词并将其用作字典键,每个后续单词都添加到列表中,该列表是前述键的值。

输入位于文件names.txt

Victor Bertha Amy Diane Erika Clare
Wyatt Diane Bertha Amy Clare Erika
Xavier Bertha Erika Clare Diane Amy
Yancey Amy Diane Clare Bertha Erika
Zeus Bertha Diane Amy Erika Clare

Amy Zeus Victor Wyatt Yancey Xavier
Bertha Xavier Wyatt Yancey Victor Zeus
Clare Wyatt Xavier Yancey Zeus Victor
Diane Victor Zeus Yancey Xavier Wyatt
Erika Yancey Wyatt Zeus Xavier Victor

例如,men["Victor"] = ["Bertha","Amy","Diane","Erika","Clare"]

代码位于文件GS.py(Gale-Shapley的实现)中:

if __name__ == "__main__":

    ## Data Dictionary

    ''' Name : Preferences '''
    men = dict()
    women = dict()

    ''' List of unmatched men '''
    freeMen = list()

    ''' Name : How far down in preferences '''
    count = dict()

    ''' Name : Current Match '''
    wife = dict()
    husband = dict()

    ## Reading Input
    data = input("").split("\n")
    print(data)
    readingMen = True
    for l in data:
        line = l.split()
        print(line)
        if len(line) > 1:
            newPerson = line[0]
            newPersonPreferences = list()
            for i in range(1,len(line)):
                newPersonPreferences.append(line[i])
            if readingMen:
                print("man")
                print(newPersonPreferences)
                men[newPerson] = newPersonPreferences
                wife[newPerson] = 0
                count[newPerson] = 0
                freeMen.append(newPerson)
            else:
                print("woman")
                print(newPersonPreferences)
                women[newPerson] = newPersonPreferences
                husband[newPerson] = 0
        elif len(line) == 1:
            raise IOError(l + "\nis an invalid line.")
        else:
            readingMen = False

    ## Proposing
    while len(freeMen) != 0:
        m = freeMen[0]
        w = men[m][count[m]]
        count[m] += 1
        if husband[w] == 0:
            husband[w] = m
            wife[m] = w
            freeMen.remove(m)
        else:
            try:
                if women[w].index(husband[w], women[w].index(m)):
                    freeMen.append(husband[w])
                    wife[husband[w]] = 0
                    husband[w] = m
                    wife[m] = w
                    freeMen.remove(m)
            except ValueError:
                pass

    ## Match Printing
    print()
    for m in wife:
        print(m, wife[m])

在Windows上使用IDLE时,我只需粘贴此文件的内容并按Enter键即可。

但是使用Ubuntu,我做python3 GS.py < names.txt我得到了这个:

me@glados:~$ python3 GS.py < names.txt
['Victor Bertha Amy Diane Erika Clare']
['Victor', 'Bertha', 'Amy', 'Diane', 'Erika', 'Clare']
man
['Bertha', 'Amy', 'Diane', 'Erika', 'Clare']
Traceback (most recent call last):
  File "GS.py", line 83, in <module>
    if husband[w] == 0:
KeyError: 'Bertha'

(已编辑)现在当我cat names.txt | python3 GS.py时,我明白这一点:

ajg9132@glados:~$ cat names.txt | python GS.py
Traceback (most recent call last):
  File "GS.py", line 50, in <module>
    data = input("").split("\n")
  File "<string>", line 1
    Victor Bertha Amy Diane Erika Clare
                ^
SyntaxError: invalid syntax

我不知道该怎么做 - 对I / O一无所知。有什么帮助吗?

编辑说明:我认为我给出的两个不同的bash命令是等价的,但是我再说一遍,我总是说菜鸟,所以解释他们为什么会有所不同会有所帮助太...

为了消除歧义,这是Algo的家庭作业......(我很难理解算法而不是操作系统的低级细节),我需要一个特定的输入和输出方案。 e.g。

spock $ java GS
Victor Bertha Amy Diane Erika Clare
Wyatt Diane Bertha Amy Clare Erika
Xavier Bertha Erika Clare Diane Amy
Yancey Amy Diane Clare Bertha Erika
Zeus Bertha Diane Amy Erika Clare

Amy Zeus Victor Wyatt Yancey Xavier
Bertha Xavier Wyatt Yancey Victor Zeus
Clare Wyatt Xavier Yancey Zeus Victor
Diane Victor Zeus Yancey Xavier Wyatt
Erika Yancey Wyatt Zeus Xavier Victor

Victor Amy
Wyatt Clare
Xavier Bertha
Yancy Erika
Zeus Diane
spock $

我没有这样做的唯一原因是因为将几行文本粘贴到PuTTY中使得bash尝试将每一行解释为命令。我甚至都不能。

1 个答案:

答案 0 :(得分:3)

input()的含义已经改变。

在Python 3.2中:http://docs.python.org/py3k/library/functions.html#input

在Python 2.7.2中:http://docs.python.org/library/functions.html#input

通过两个小型测试程序,您可以更轻松地看到这一点。唯一的区别是一个使用Python 2.7解释器,另一个使用Python 3.2解释器:

$ cat input27.py 
#!/usr/bin/python2.7
data = input("")

for l in data.split("\n"):
    print(l)
$ cat input32.py 
#!/usr/bin/python3.2
data = input("")

for l in data.split("\n"):
    print(l)
$ ./input27.py < names.txt 
Traceback (most recent call last):
  File "./input27.py", line 2, in <module>
    data = input("")
  File "<string>", line 1
    Victor Bertha Amy Diane Erika Clare
                ^
SyntaxError: invalid syntax
$ ./input32.py < names.txt 
Victor Bertha Amy Diane Erika Clare
$ 

请注意,即使Python 3.2版本没有抛出错误,它也不会按照人们的预期打印names.txt中的所有行。

我认为input()方法不值得使用。更容易使用新的for line in file:方法:

$ cat fixed_input27.py 
#!/usr/bin/python2.7

import sys

for line in sys.stdin:
    print(line.split()[0])
$ cat fixed_input32.py 
#!/usr/bin/python3.2

import sys

for line in sys.stdin:
    print(line.split()[0])
$ ./fixed_input27.py < names.txt 
Victor
Wyatt
Xavier
Yancey
Zeus
Amy
Bertha
Clare
Diane
Erika
$ ./fixed_input32.py < names.txt 
Victor
Wyatt
Xavier
Yancey
Zeus
Amy
Bertha
Clare
Diane
Erika
$ 

(我删除了names.txt中的一个空白行,因为它导致这个简单的程序抛出错误。在你的完整程序中实际上不会出现问题,因为你正确处理空行。)

我无法解释为什么input() 在Windows下工作,但是input()感觉就像一个非常糟糕的界面(他认为通过{{运行用户提供的输入) 1}}是一个好主意?!?sheesh)只是重写它。

<强>更新

好的,我很感兴趣,一直都能解决这个问题。我将所有调试代码退回并切换到使用eval方法:

for l in sys.stdin:

请注意,如果以这种方式运行,则必须在粘贴输入时点击$ ./GS.py Victor Bertha Amy Diane Erika Clare Wyatt Diane Bertha Amy Clare Erika Xavier Bertha Erika Clare Diane Amy Yancey Amy Diane Clare Bertha Erika Zeus Bertha Diane Amy Erika Clare Amy Zeus Victor Wyatt Yancey Xavier Bertha Xavier Wyatt Yancey Victor Zeus Clare Wyatt Xavier Yancey Zeus Victor Diane Victor Zeus Yancey Xavier Wyatt Erika Yancey Wyatt Zeus Xavier Victor Wyatt Clare Xavier Bertha Yancey Erika Zeus Diane Victor Amy $ cat GS.py #!/usr/bin/python3.2 if __name__ == "__main__": import sys ## Data Dictionary ''' Name : Preferences ''' men = dict() women = dict() ''' List of unmatched men ''' freeMen = list() ''' Name : How far down in preferences ''' count = dict() ''' Name : Current Match ''' wife = dict() husband = dict() ## Reading Input readingMen = True for l in sys.stdin: line = l.split() if len(line) > 1: newPerson = line[0] newPersonPreferences = list() for i in range(1,len(line)): newPersonPreferences.append(line[i]) if readingMen: men[newPerson] = newPersonPreferences wife[newPerson] = 0 count[newPerson] = 0 freeMen.append(newPerson) else: women[newPerson] = newPersonPreferences husband[newPerson] = 0 elif len(line) == 1: raise IOError(l + "\nis an invalid line.") else: readingMen = False ## Proposing while len(freeMen) != 0: m = freeMen[0] w = men[m][count[m]] count[m] += 1 if husband[w] == 0: husband[w] = m wife[m] = w freeMen.remove(m) else: try: if women[w].index(husband[w], women[w].index(m)): freeMen.append(husband[w]) wife[husband[w]] = 0 husband[w] = m wife[m] = w freeMen.remove(m) except ValueError: pass ## Match Printing print() for m in wife: print(m, wife[m]) $ 。 (我很多更喜欢IO重定向^D,但如果你的教授会复制并粘贴,那么请确保你的教授知道点击./GS.py < names.txt以表示输入的结束。)< / p>