2013-04-23 53 views
4

好的,我一直在编写一个脚本(在这里有很多帮助),它的工作(实质上是脚本更新静态服务器上的html文件,即没有PHP ,所以我可以改变菜单,侧边栏等等),但是输入部分会出现一个烦人的事情。根据哪台计算机或哪个版本的python,我需要为我的输入包含引号,否则我不需要。在我的Linux笔记本电脑上,我需要引号;在Windows笔记本电脑(只有python3.3)上,我不需要引号;在已经有2.5,2.7和现在3.3的Windows桌面上,当我在命令行中运行它时(即使它通过C:\ Python33 \ py.exe运行),但在IDLE中不需要引号时?这很奇怪......Python,从输入中删除所需的引号()

import os 
import glob 
import fileinput 

if __name__ == '__main__': 
    # Menu should not have any marker, just pure contents 
    with open(input('Enter Update File: ')) as f: 
     menu_contents = f.read() 

    # Initialize a few items 
    start_marker = '<!--begin-menu-->' 
    end_marker = '<!--end-menu-->' 
    file_list = [] 
    for root, dirs, files in os.walk(input('Enter Directory: ')): 
       file_list += glob.glob(os.path.join(root, '*.html')) 
    found_old_contents = False 

    # Loop to replace text in place 
    for line in fileinput.input(file_list, inplace=True): 
     line = line.rstrip() 

     if line == start_marker: 
      found_old_contents = True 
      print(line) 
      print(menu_contents) 
     elif line == end_marker: 
      found_old_contents = False 

     if not found_old_contents: 
      print(line) 

有没有办法避免这种情况?

否则,我想我会开始研究如何调用一个资源管理器对话框,以便我可以选择一个文件和一个文件夹......对此有何想法?

+3

的Python 2和Python 3是不一样的语言。不要在Python 2中使用'input()',也不要试图在两者上使用相同的代码库。 – geoffspear 2013-04-23 17:45:44

+0

澄清:你的input()在某个系统上需要引号? – 2013-04-23 17:48:58

+0

是的,但我想它与文件关联有关......也许。一台只有3.3的电脑,不需要报价。我的linux机器上一次可能有2.7个,我知道我在其他的Windows桌面上有2.5和2.7。现在,我只是继续前进,研究使它弹出一个浏览器窗口,而不是... – rickman90 2013-04-23 18:02:16

回答

9

在Python 2.x上,您需要使用raw_input()而不是input()。在旧版本的Python中,input()实际上评估你输入作为Python表达式,这就是为什么你需要引号(就像你在Python程序中编写字符串一样)。

Python 3.x和Python 2.x之间有许多区别;这只是其中之一。但是,你可以工作的代码周围这个特定的差异这样的:

try: 
    input = raw_input 
except NameError: 
    pass 

# now input() does the job on either 2.x or 3.x 
+0

杰出!那就是诀窍。谢谢! – rickman90 2013-04-23 18:19:26

+0

@ rickman90请考虑接受答案,如果它解决了你的问题。这是如何:http://meta.stackexchange.com/a/5235/161449 – 2013-04-24 07:05:57