简体   繁体   English

Python - 保持命令窗口打开以查看结果

[英]Python - Keep command window open to see results

I have a text file (test.txt) that contains 我有一个包含的文本文件(test.txt)

text1 text2 text text text

Below is my code: 以下是我的代码:

import codecs
BOM = codecs.BOM_UTF8.decode('utf8')
name = (raw_input("Please enter the name of the file: "))

with codecs.open(name, encoding='utf-8') as f:
    words=[]            #define words here
    for line in f:
        line = line.lstrip(BOM)
        words.extend(line.split())        #append words from each line to words  

if len(words) > 2:
    print 'There are more than two words'
    firstrow = words[:2]
    print firstrow                #indentation problem here
elif len(words) <2:                    #use if
    print 'There are under 2 words, no words will be shown'

raw_input("Press return to close this window...")

When I run the .py file, I want to keep the command window open so I can see all the prints, but for some reason it closes right away, when I run this in shell it works. 当我运行.py文件时,我想保持命令窗口打开,这样我就能看到所有的打印件,但由于某种原因,它会立即关闭,当我在shell中运行它时,它可以工作。 For some reasoning the raw_input is not working like it normally has for me. 由于某种原因,raw_input不像我通常那样工作。 Its my 2nd day at python so I am still a newbie! 这是我在python的第二天,所以我还是一个新手!

Thanks in advance for the help 先谢谢您的帮助

Newbie question, newbie answer!! 新手问题,新手回答!!

I didnt have my text file in the directory of my .py only in my shell path which is why it was working there. 我没有在我的.py目录中的文本文件只在我的shell路径中,这就是为什么它在那里工作。

You should put at least the file reading code in a try/except block, so you can see what errors occur; 您应该至少将文件读取代码放在try / except块中,这样您就可以看到发生了什么错误;

import codecs

BOM = codecs.BOM_UTF8.decode('utf8')
name = raw_input("Please enter the name of the file: ")

try:
  with codecs.open(name, encoding='utf-8') as f:
    words=[]            #define words here
    for line in f:
        line = line.lstrip(BOM)
        words.extend(line.split())
except Exception as details:
  print "Unexpected error:", details
  raw_input("Press return to close this window...")
  exit(1)

if len(words) > 2:
    print 'There are more than two words'
    firstrow = words[:2]
    print firstrow
elif len(words) <2:                    #use if
    print 'There are under 2 words, no words will be shown'

raw_input("Press return to close this window...")

If I try this with a nonexisting filename: 如果我尝试使用不存在的文件名:

Please enter the name of the file: bla
Unexpected error: [Errno 2] No such file or directory: 'bla'
Press return to close this window...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM