IOError:Filename,foldername或volumename语法错误

时间:2013-02-17 10:24:56

标签: python ioerror

我无法执行代码,就像

Transmission calls TorrentToMedia.bat F:/Downloaded/_automated/test/complete/tv My.Very.Legal.Download.S01E01.720p.HDTV.x264-FiHTV

然后传递给python脚本,

TorrentToMedia.py F:/Downloaded/_automated/test/complete/tv My.Very.Legal.Download.S01E01.720p.HDTV.x264-FiHTV

调试日志:

C:\Windows\system32>python C:\Downloaders\nzbToMedia\torrenttomedia.py F:\Downlo
aded_automated\test\complete\tv 8.Out.Of.10.Cats.S15E05.720p.HDTV.x264-TLA
03:35:25|INFO TorrentToMedia V4.3
03:35:25|INFO Script called from Transmission
03:35:25|INFO Loading config from C:\Downloaders\nzbToMedia\autoProcessMedia.cfg
03:35:25|INFO Found torrent directory F:\Downloaded_automated\test\complete\tv\8.Out.Of.10.Cats.S15E05.720p.HDTV.x264-TLA in category directory F:\Downloaded_automated\test\complete\tv
03:35:25|INFO Determined Category to be: tv
03:35:25|INFO Found media files
03:35:25|INFO Creating hardlink for files from F:\Downloaded_automated\test\complete\tv\8.Out.Of.10.Cats.S15E05.720p.HDTV.x264-TLA to F:/Downloaded/_automated/test/process/tv\8.Out.Of.10.Cats.S15E05.720p.HDTV.x264-TLA.
Traceback (most recent call last):
File "C:\Downloaders\nzbToMedia\torrenttomedia.py", line 186, in 
linktastic.link(source, target)
File "C:\Downloaders\nzbToMedia\linktastic.py", line 65, in link
_link_windows(src, dest)
File "C:\Downloaders\nzbToMedia\linktastic.py", line 41, in _link_windows
raise IOError(err.output.decode('utf-8'))
IOError: Filename, foldername or volumename syntax is wrong.

现在我得到的错误是当我拨打linktastic.link(source, target)

TorrentTomMedia.py

#!/usr/bin/env python

import autoProcessMovie
import autoProcessTV
import sys, os, ConfigParser, shutil
import logging, logging.config
import linktastic

from nzbToMediaEnv import *

Logger = logging.getLogger()
logFile = os.path.join(os.path.dirname(sys.argv[0]), "postprocess.log")
logging.config.fileConfig(os.path.join(os.path.dirname(sys.argv[0]), "logger.conf"))
fileHandler = logging.FileHandler(logFile, encoding='utf-8', delay=True)
fileHandler.formatter = logging.Formatter('%(asctime)s|%(levelname)-7.7s %(message)s', '%H:%M:%S')
fileHandler.level = logging.DEBUG
Logger.addHandler(fileHandler)

def removeEmptyFolders(path):
    if not os.path.isdir(path):
        return

    # remove empty subfolders
    files = os.listdir(path)
    if len(files):
        for f in files:
            fullpath = os.path.join(path, f)
            if os.path.isdir(fullpath):
                removeEmptyFolders(fullpath)

    # if folder empty, delete it
    files = os.listdir(path)
    if len(files) == 0:
        Logger.info("Removing empty folder: %s", path)
        os.rmdir(path)

Logger.info("TorrentToMedia %s", VERSION)

if len(sys.argv) == 3:
    # I've now merged Transmission and uTorrent into on "universal" solution. 
    # We will use paramters,
    # %D (from uTorrent) or %TR_TORRENT_DIR% (from Transmission) as torrent directory
    # %N (from uTorrent) or %TR_TORRENT_NAME% (from Transmission) as torrent name
    # and parse the directory tree to match categorys (tv, movie).
    # So in uTorrent use, python C:/path/to/nzbToMedia/TorrentToMedia.py %D %N
    # and with Transmission use the included TorrentToMedia.sh (for linux) or TorrentToMedia.bat (for Windows)
    # script files to launch TorrentToMedia.py

    Directory = sys.argv[1]
    Name = sys.argv[2]
    Logger.info("Script called from Transmission")
    Category = '' #We dont have a category, we will determine it later.

else:
    # We dont know which client the call is comeing from, aborting
    Logger.error("Cant load variables, aborting.")
    sys.exit(-1)

Logger.debug("Received Directory: %s", Directory)
Logger.debug("Received Torrent Name: %s", Name)

status = 0
packed = 0
root = 0
video = 0

config = ConfigParser.ConfigParser()
configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessMedia.cfg")

Logger.info("Loading config from %s", configFilename)

if not os.path.isfile(configFilename):
    Logger.error("You need an autoProcessMedia.cfg file - did you rename and edit the .sample?")
    sys.exit(-1)

config.read(configFilename)

TV_Cat = config.get("SickBeard", "category")
TV_dest = config.get("SickBeard", "destination")
Movie_dest = config.get("CouchPotato", "destination")
Movie_Cat = config.get("CouchPotato", "category")
useLink = int(config.get("Torrent", "uselink"))
extractionTool = config.get("Torrent", "extractiontool")

DirBase = os.path.split(os.path.normpath(Directory)) #Test for blackhole sub-directory.
if DirBase[1] == Name:
    Logger.info("Files appear to be in their own directory")
    DirBase2 = os.path.split(os.path.normpath(DirBase[0]))
    if DirBase2[1] == Movie_Cat or DirBase2[1] == TV_Cat:
        if not Category:
            Logger.info("Determined Category to be: %s", DirBase2[1])
            Category = DirBase2[1]

elif DirBase[1] == Movie_Cat or DirBase[1] == TV_Cat:
    if os.path.isdir(os.path.join(Directory, Name)):
        Logger.info("Found torrent directory %s in category directory %s", os.path.join(Directory, Name), Directory)
        Directory = os.path.join(Directory, Name)
    else:
        Logger.info("The directory passed is the root directory for category %s", DirBase[1])
        Logger.warn("You should change settings to download torrents to their own directory")
        Logger.info("We will try and determine which files to process, individually")
        root = 1
    if not Category:
        Logger.info("Determined Category to be: %s", DirBase[1])
        Category = DirBase[1]

else: # no category found in directory. For Utorrent we can do a recursive scan.
    Logger.info("The directory passed does not appear to include a category or the torrent name")
    Logger.warn("You should change settings to download torrents to their own directory")
    Logger.info("We will try and determine which files to process, individually")
    root = 1

if Category == Movie_Cat:
    destination = os.path.join(Movie_dest, Name)
elif Category == TV_Cat:
    destination = os.path.join(TV_dest, Name)
else:
    Logger.info("Category of %s does not match either %s or %s: Exiting", Category, Movie_Cat, TV_Cat)
    sys.exit(-1)

# Check if destination directory exists
if not os.path.isdir(destination):
        os.mkdir(destination)
        Logger.debug("Creating destination directory %s", destination)
    else:
        Logger.debug("Destination directory already exists, %s", destination)

test = ['.zip', '.rar', '.7z', '.gz', '.bz', '.tar', '.arj']
test2 = ['.mkv', '.avi', '.divx', '.xvid', '.mov', '.wmv', '.mp4', '.mpg', '.mpeg']
Logger.debug("Scanning files in directory: %s", Directory)
f = [filenames for dirpath, dirnames, filenames in os.walk(Directory)]
if root == 1:
    Logger.debug("Looking for %s in filenames", Name)
    for file in f[1]:
        if (Name in file) or (file in Name):
            if os.path.splitext(file)[1] in test:
                Logger.info("Found a packed file %s", file)
                packed = 1
                break
            elif os.path.splitext(file)[1] in test2:
                Logger.info("Found a video file %s", file)
                video = 1
                break
            else:
                continue
else:
    ext = [os.path.splitext(file)[1] for file in f[1]]
    if set(ext).intersection(set(test)):
        Logger.info("Found compressed archives, extracting")
        packed = 1
    ## Check that files actully is .mkv / .avi etc, and not packed files or anything else
    elif set(ext).intersection(set(test2)):
        Logger.info("Found media files")
        video = 1
    else:
        Logger.debug("Found files with extensions %s.", ext)
        Logger.debug("Looking for extensions %s or %s.", test, test2)
        Logger.info("Didn't find any compressed archives or media files to process, exiting")
        sys.exit(-1)

if useLink == 0 and packed == 0 and video == 1: ## copy
    if root == 0: #move all files in tier own directory 
        Logger.info("Copying all files from %s to %s.", Directory, destination)
        shutil.copytree(Directory.lower(), destination.lower())
    else: #we only want to move files matching the torrent name when root directory is used.
        for dirpath, dirnames, filenames in os.walk(Directory):
            for file in filenames:
                if (Name in file) or (file in Name):
                    pass
                else:
                    continue #ignore the other files
                source = os.path.join(dirpath, file)
                target = os.path.join(destination, file)
                Logger.info("Copying files that match the torrent name %s from %s to %s.", Name, Directory, file, destination, file)
                shutil.copy(source, target)

elif useLink == 1 and packed == 0 and video == 1: ## hardlink
    for dirpath, dirnames, filenames in os.walk(Directory):
        for file in filenames:
            if root == 1: #we only want to move files matching the torrent name when root directory is used.
                if (Name in file) or (file in Name):
                    pass
                else:
                    continue #ignore the other files
            source = os.path.join(dirpath, file)
            target = os.path.join(destination, file)
            Logger.info("Creating hardlink for files from %s to %s.", source, target)
            linktastic.link(source, target)

elif packed == 1: ## unpack
    ## Using Windows?
    if os.name == 'nt':
        cmd_7zip = [extractionTool, 'x -y']
        ext_7zip = [".rar",".zip",".tar.gz","tgz",".tar.bz2",".tbz",".tar.lzma",".tlz",".7z",".xz"]
        EXTRACT_COMMANDS = dict.fromkeys(ext_7zip, cmd_7zip)
        Logger.info("We are using Windows")

    ## Using linux?
    elif os.name == 'posix':
        required_cmds=["unrar", "unzip", "tar", "unxz", "unlzma", "7zr"]
        EXTRACT_COMMANDS = {
        ".rar": ["unrar", "x -o+ -y"],
        ".zip": ["unzip", ""],
        ".tar.gz": ["tar", "xzf"],
        ".tgz": ["tar", "xzf"],
        ".tar.bz2": ["tar", "xjf"],
        ".tbz": ["tar", "xjf"],
        ".tar.lzma": ["tar", "--lzma xf"],
        ".tlz": ["tar", "--lzma xf"],
        ".txz": ["tar", "--xz xf"],
        ".7z": ["7zr", "x"],
        }
        Logger.info("We are using *nix")

    ## Need to add a check for which commands that can be utilized in *nix systems..
    else:
        Logger.error("Unknown OS, exiting")

    files = [ f for f in os.listdir(Directory) if os.path.isfile(os.path.join(Directory,f)) ]
    for f in files:
        if root == 1: #we only want to move files matching the torrent name when root directory is used.
            if (Name in file) or (file in Name):
                pass
            else:
                continue #ignore the other files
        ext = os.path.splitext(f)
        fp = os.path.join(Directory, os.path.normpath(f))
        if ext[1] in (".gz", ".bz2", ".lzma"):
        ## Check if this is a tar
            if os.path.splitext(ext[0])[1] == ".tar":
                cmd = EXTRACT_COMMANDS[".tar" + ext[1]]
        else:
            if ext[1] in EXTRACT_COMMANDS:
                cmd = EXTRACT_COMMANDS[ext[1]]
            else:
                Logger.debug("Unknown file type: %s", ext[1])
                continue

        ## Create destination folder
        if not os.path.exists(destination):
            try:
                os.makedirs(destination)
            except Exception, e:
                Logger.error("Not possible to create destination folder: %s", e)
                continue

        Logger.info("Extracting to %s", destination)

        ## Running..
        Logger.info("Extracting %s %s %s %s", cmd[0], cmd[1], fp, destination)
        pwd = os.getcwd() # Get our Present Working Directory
        os.chdir(destination) #not all unpack commands accept full paths, so just extract into this directory.
        if os.name == 'nt': #Windows needs quotes around directory structure
            try:
                run = "\"" + cmd[0] + "\" " + cmd[1] + " \"" + fp + "\"" #windows needs quotes around directories.
                res = call(run)
                if res == 0:
                    status = 0
                    Logger.info("Extraction was successful for %s to %s", fp, destination)
                else:
                    Logger.info("Extraction failed for %s. 7zip result was %s", fp, res)
            except:
                Logger.error("Extraction failed for %s. Could not call command %s %s", fp, run)
        else:
            try:
                if cmd[1] == "": #if calling unzip, we dont want to pass the ""
                    res = call([cmd[0], fp])
                else:
                    res = call([cmd[0], cmd[1], fp])
                if res == 0:
                    status = 0
                    Logger.info("Extraction was successful for %s to %s", fp, destination)
                else:
                    Logger.error("Extraction failed for %s. 7zip result was %s", fp, res)
            except:
                Logger.error("Extraction failed for %s. Could not call command %s %s %s %s", fp, cmd[0], cmd[1], fp)    
        os.chdir(pwd) # Go back to our Original Working Directory

for dirpath, dirnames, filenames in os.walk(destination): #flatten out the directory to make postprocessing easier.
    if dirpath == destination:
        continue #no need to try and move files in the root destination directory.
    for filename in filenames:
        try:
            shutil.move(os.path.join(dirpath, filename), destination)
        except OSError:
            Logger.info("Could not flatten %s", os.path.join(dirpath, filename))
removeEmptyFolders(destination) #cleanup empty directories.

status = int(status)
if status == 0:
    Logger.info("calling autoProcess script for successful download")
else:
    Logger.info("calling autoProcess script for failed download")
## Now we pass off to CouchPotato or SickBeard.
old_stdout = sys.stdout #backup the default stdout
sys.stdout = Logger.info #Capture the print from the autoProcess scripts.
if Category == Movie_Cat:  
    autoProcessMovie.process(destination, Name, status)
elif Category == TV_Cat:
    autoProcessTV.processEpisode(destination, Name, status)
sys.stdout = old_stdout #reset our stdout

linktastic.py

# Linktastic Module
# - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems
#
# Linktastic is distributed under the MIT License.  The follow are the terms and conditions of using Linktastic.
#
# The MIT License (MIT)
#  Copyright (c) 2012 Solipsis Development
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import subprocess
from subprocess import CalledProcessError
import os


# Prevent spaces from messing with us!
def _escape_param(param):
    return '"%s"' % param


# Private function to create link on nt-based systems
def _link_windows(src, dest):
    try:
        subprocess.check_output(
            ['cmd', '/C', 'mklink', '/H', _escape_param(dest), _escape_param(src)],
            stderr=subprocess.STDOUT)
    except CalledProcessError as err:
        raise IOError(err.output.decode('utf-8'))

    # TODO, find out what kind of messages Windows sends us from mklink
    # print(stdout)
    # assume if they ret-coded 0 we're good


def _symlink_windows(src, dest):
    try:
        subprocess.check_output(
            ['cmd', '/C', 'mklink', _escape_param(dest), _escape_param(src)],
            stderr=subprocess.STDOUT)
    except CalledProcessError as err:
        raise IOError(err.output.decode('utf-8'))

    # TODO, find out what kind of messages Windows sends us from mklink
    # print(stdout)
    # assume if they ret-coded 0 we're good


# Create a hard link to src named as dest
# This version of link, unlike os.link, supports nt systems as well
def link(src, dest):
    if os.name == 'nt':
        _link_windows(src, dest)
    else:
        os.link(src, dest)


# Create a symlink to src named as dest, but don't fail if you're on nt
def symlink(src, dest):
    if os.name == 'nt':
        _symlink_windows(src, dest)
    else:
        os.symlink(src, dest)

您可以在此处查看linktastic lib和TorrentToMedia.py,https://github.com/jkaberg/nzbToMedia

真的很感激一些输入和帮助,现在已经持续了好几个小时而没有进一步提出

1 个答案:

答案 0 :(得分:0)

看起来这就是问题:

03:35:25|INFO Creating hardlink for files from       
F:\Downloaded_automated\test\complete\tv\8.Out.Of.10.Cats.S15E05.720p.HDTV.x264-TLA to    
F:/Downloaded/_automated/test/process/tv\8.Out.Of.10.Cats.S15E05.720p.HDTV.x264-TLA.

注意最后一条路径的前向和反斜杠是如何混合的。

顺便说一句,10只猫中有8只FTW; - )

相关问题