Python 2.7 给我莫名其妙的 "syntax errors"

标签 python string python-2.7 syntax

我在 python3.3 中写了一个脚本来同步 Windows 上的两个目录,效果很好;后来我想让它成为一个可执行文件,所以我将它移植到 python 2.7(cx_freeze 给我“找不到模块”错误)。不过,我遇到了这个奇怪的问题,每当我输入程序的文件路径时,它都会给我一个错误;例如,如果我输入“C:\Users\Me\SourceDir”,程序就会中断,输出

File "<string>", line 1
C:\Users\Me\SourceDir
 ^
Syntax Error: Invalid Syntax

我很困惑为什么会这样。该程序在 python3.3 下运行良好(路径相同,我应该补充一下),这让我相信 2.7 在幕后发生了一些奇怪的事情。

任何人都可以向我解释为什么会发生这种情况以及如何解决它吗?

还有程序的源代码,虽然我觉得这并不重要

    '''
Created on Mar 18, 2013

@author: pipsqueaker
'''
import os, shutil, time
from datetime import datetime

class mainClass():

    def __init__(self):
        self.srcDir = []
        self.dst = []
        self.iteration = 1
        self.fileHash = {}
        self.slash  = ""

    def getParentDir(self, string, slash):
        slashCount = 0
        tempCount = 0
        realDir = ""
        for x in string:
            if x == "/" or x == "\\":
                slashCount += 1
        for y in string:
            if y == "/" or y == "\\":
                tempCount += 1
            if tempCount < slashCount:
                realDir += y
            else:
                break
        realDir += slash
        return realDir

    def initializeDirs(self):
        #Initialize Paths from the setup files
        onWindows = (os.name == 'nt')
        if onWindows:
            self.slash = "\\"
        else:
            self.slash = "/"

        os.chdir(self.getParentDir(os.path.realpath(__file__), self.slash))

        if os.path.exists("srcDir") == False:
            print("The srcDir file does not exist; Creating Now...")
            self.srcDir = input("Please input source directory \n")
            self.newSource = open("srcDir", "w")
            if self.srcDir[self.srcDir.__len__() -1] != self.slash:
                self.srcDir += self.slash
            self.newSource.write(self.srcDir)
            self.newSource.close()

        if os.path.exists("dstDirs") == False:
            print("The dstFirs file does not exits; Creating Now...")
            print("Input a directory to sync to. Or just type xit to exit")

            self.newDst = open("dstDirs", "w")
            while True:
                self.IN = input()
                if os.name == 'nt': #Windows
                    self.IN.replace("/", "\\")
                else:
                    self.IN.replace("\\", "/")

                if self.IN != "xit":
                    if self.IN[self.IN.__len__() -1] != self.slash:
                        self.IN += self.slash
                    self.newDst.write(self.IN)
                    self.dst.append(self.IN)
                else:
                    self.newDst.close()
                    break

        self.srcDir = open("srcDir", "r")
        self.srcDir = self.srcDir.readline()

        self.dstDirs = open("dstDirs", "r")
        for line in self.dstDirs:
            self.dst.append(line)

    def fileHashes(self):
        self.fileHash = {}   
        for file in os.listdir(self.srcDir):
            self.fileHash[file] = os.path.getmtime(self.srcDir+file)

    def loopForever(self):
        print("Filesync Version 1.0 by pipsqueaker \n")
        while True:
            print("Iteration ", self.iteration, " @ ", datetime.now()) #APPROVE

            for destination in self.dst:
                for checkFile in os.listdir(destination):
                    if not os.path.exists(self.srcDir+checkFile):
                        os.remove(destination+checkFile)
                        print(checkFile, " removed from ", destination, " @", datetime.now())
                        self.fileHashes()

                for file in os.listdir(self.srcDir):

                    if os.path.exists(destination+file):
                        try:
                            if os.path.getmtime(self.srcDir+file) != self.fileHash[file]:
                                    try:
                                        shutil.copy2((self.srcDir+file), destination)
                                        print(file," was updated to ",destination," @",datetime.now())
                                    except:
                                        pass

                        except KeyError:
                            continue
                    else:
                        try:
                            shutil.copy2((self.srcDir+file), destination)
                            print(file, " was copied to ", destination, " @", datetime.now())
                            self.fileHashes()
                        except:
                            pass
            self.iteration += 1
            time.sleep(10)

    def main(self):
        self.initializeDirs()
        self.fileHashes()
        self.loopForever()

n = mainClass()
n.main()

最佳答案

您正在脚本中使用 input():

self.IN = input()

Python 2 对此有 raw_input()。 python 2 中的 input()eval(raw_input()) 相同。尝试评估路径肯定会导致语法错误。

hello 因为输入会导致语法错误(除非你在范围内有一个名为 hello 的变量)。 "hello" 确实会计算出字符串“hello”。就像 python 中的简单表达式一样。

您可能想看一下 2to3 tool .

关于Python 2.7 给我莫名其妙的 "syntax errors",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16726601/

相关文章:

javascript - 没有全局标志的正则表达式分组 OR 运算符匹配策略

c# - 匹配整个单词或短语的正则表达式

python-2.7 - 如何在 Matplotlib (Numpy) 中生成 MATLAB 图(插值)?

python - 类型错误 : Argument given by name "id" and position(2) -- wxPython

python - 在新的终端窗口中打印

java - 检查字符串中的一组特定字符(密码)

python - 多线程XML-RPC (python3.7.1)

Python 看不到使用 apt-get 安装的模块

python - Django 表单图像字段出现在 self.data 中但没有出现在 self.cleaned_data 中

python - 合并 2 个字典并将它们存储在 pandas 数据框中,其中一个字典具有可变长度列表元素