diff options
author | Walter Purcaro <vuolter@users.noreply.github.com> | 2015-05-12 02:00:28 +0200 |
---|---|---|
committer | Walter Purcaro <vuolter@users.noreply.github.com> | 2015-05-12 03:22:29 +0200 |
commit | 0349b81a10d2937897f30031c4dedb49aa132d8c (patch) | |
tree | 3db2827cd64888cc013e064d4e201b8a6ddbc7a9 | |
parent | Merge pull request #12 from GammaC0de/GammaC0de-fix-api (diff) | |
download | pyload-0349b81a10d2937897f30031c4dedb49aa132d8c.tar.xz |
'from os' -> 'import os' and so on...
28 files changed, 173 insertions, 202 deletions
diff --git a/pyload/Core.py b/pyload/Core.py index 2b356b9fb..231959b07 100755 --- a/pyload/Core.py +++ b/pyload/Core.py @@ -19,8 +19,6 @@ import pyload.utils.pylgettext as gettext from codecs import getwriter from getopt import getopt, GetoptError from imp import find_module -from os import _exit, execl, getcwd, makedirs, remove, sep, walk, chdir, close -from os.path import exists, join from sys import argv, executable, exit from time import time, sleep @@ -161,7 +159,7 @@ class Core(object): def quit(self, a, b): self.shutdown() self.log.info(_("Received Quit signal")) - _exit(1) + os._exit(1) def writePidFile(self): @@ -217,10 +215,10 @@ class Core(object): t = time() print "waiting for pyLoad to quit" - while exists(self.pidfile) and t + 10 > time(): + whileself.pidfile) and t + 10 > time(): sleep(0.25) - if not exists(self.pidfile): + if not os.path.exists(self.pidfile): print "pyLoad successfully stopped" else: os.kill(pid, 9) #: SIGKILL @@ -232,7 +230,7 @@ class Core(object): def cleanTree(self): - for path, dirs, files in walk(self.path("")): + for path, dirs, files in os.walk(self.path("")): for f in files: if not f.endswith(".pyo") and not f.endswith(".pyc"): continue @@ -240,8 +238,8 @@ class Core(object): if "_25" in f or "_26" in f or "_27" in f: continue - print join(path, f) - reshutil.move(join(path, f)) + print os.path.join(path, f) + reshutil.move(os.path.join(path, f)) def start(self, rpc=True, web=True): @@ -249,7 +247,7 @@ class Core(object): self.version = pyload.__version__ - if not exists("pyload.conf"): + if not os.path.exists("pyload.conf"): from pyload.config.Setup import SetupAssistant as Setup print "This is your first start, running configuration assistent now." @@ -325,7 +323,7 @@ class Core(object): self.shuttedDown = False self.log.info(_("Starting") + " pyLoad %s" % pyload.__version__) - self.log.info(_("Using home directory: %s") % getcwd()) + self.log.info(_("Using home directory: %s") % os.getcwd()) self.writePidFile() @@ -400,15 +398,15 @@ class Core(object): self.config.save() #: save so config files gets filled - link_file = join(pypath, "links.txt") + link_file = os.path.join(pypath, "links.txt") - if exists(link_file): + if os.path.exists(link_file): with open(link_file, "rb") as f: if f.read().strip(): self.api.addPackage("links.txt", [link_file], 1) link_file = "links.txt" - if exists(link_file): + if os.path.exists(link_file): with open(link_file, "rb") as f: if f.read().strip(): self.api.addPackage("links.txt", [link_file], 1) @@ -436,7 +434,7 @@ class Core(object): self.shutdown() self.log.info(_("pyLoad quits")) self.removeLogger() - _exit(0) #@TODO thrift blocks shutdown + os._exit(0) #@TODO thrift blocks shutdown self.threadManager.work() self.scheduler.work() @@ -497,18 +495,18 @@ class Core(object): self.log.addHandler(console) log_folder = self.config.get("log", "log_folder") - if not exists(log_folder): - makedirs(log_folder, 0700) + if not os.path.exists(log_folder): + os.makedirs(log_folder, 0700) # Set file handler formatter if self.config.get("log", "file_log"): if self.config.get("log", "log_rotate"): - file_handler = logging.handlers.RotatingFileHandler(join(log_folder, 'log.txt'), + file_handler = logging.handlers.RotatingFileHandler(os.path.join(log_folder, 'log.txt'), maxBytes=self.config.get("log", "log_size") * 1024, backupCount=int(self.config.get("log", "log_count")), encoding="utf8") else: - file_handler = logging.FileHandler(join(log_folder, 'log.txt'), encoding="utf8") + file_handler = logging.FileHandler(os.path.join(log_folder, 'log.txt'), encoding="utf8") file_handler.setFormatter(fh_frm) self.log.addHandler(file_handler) @@ -548,13 +546,13 @@ class Core(object): file_created = True file_exists = True for tmp_name in tmp_names: - if not exists(tmp_name): + if not os.path.exists(tmp_name): file_exists = False if empty: try: if folder: tmp_name = tmp_name.replace("/", sep) - makedirs(tmp_name) + os.makedirs(tmp_name) else: open(tmp_name, "w") except Exception: @@ -582,16 +580,16 @@ class Core(object): def restart(self): self.shutdown() - chdir(owd) + os.chdir(owd) # close some open fds for i in xrange(3, 50): try: - close(i) + os.close(i) except Exception: pass - execl(executable, executable, *sys.argv) - _exit(0) + os.execl(executable, executable, *sys.argv) + os._exit(0) def shutdown(self): @@ -621,8 +619,8 @@ class Core(object): self.deletePidFile() - def path(self, *args): - return join(pypath, *args) + def os.path(self, *args): + return os.path.join(pypath, *args) def deamon(): @@ -675,7 +673,7 @@ def main(): pyload_core.shutdown() pyload_core.log.info(_("killed pyLoad from Terminal")) pyload_core.removeLogger() - _exit(1) + os._exit(1) # And so it begins... if __name__ == "__main__": diff --git a/pyload/Thread/Addon.py b/pyload/Thread/Addon.py index bf3b62eb1..49d470a8a 100644 --- a/pyload/Thread/Addon.py +++ b/pyload/Thread/Addon.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- # @author: RaNaN +import os import traceback from Queue import Queue from copy import copy -from os import listdir, stat -from os.path import join from pprint import pformat from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime diff --git a/pyload/Thread/Decrypter.py b/pyload/Thread/Decrypter.py index dcb18b929..62891433e 100644 --- a/pyload/Thread/Decrypter.py +++ b/pyload/Thread/Decrypter.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- # @author: RaNaN +import os import traceback from Queue import Queue from copy import copy -from os import listdir, stat -from os.path import join from pprint import pformat from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime diff --git a/pyload/Thread/Download.py b/pyload/Thread/Download.py index 77f4f163f..be9a1c7ef 100644 --- a/pyload/Thread/Download.py +++ b/pyload/Thread/Download.py @@ -1,14 +1,13 @@ # -*- coding: utf-8 -*- # @author: RaNaN +import os import traceback import pycurl from Queue import Queue from copy import copy -from os import listdir, stat -from os.path import join from pprint import pformat from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime diff --git a/pyload/Thread/Info.py b/pyload/Thread/Info.py index db1b6d79c..fbd60908e 100644 --- a/pyload/Thread/Info.py +++ b/pyload/Thread/Info.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- # @author: RaNaN +import os import traceback from Queue import Queue from copy import copy -from os import listdir, stat -from os.path import join from pprint import pformat from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime diff --git a/pyload/Thread/Plugin.py b/pyload/Thread/Plugin.py index f8cfba9c4..264deb84c 100644 --- a/pyload/Thread/Plugin.py +++ b/pyload/Thread/Plugin.py @@ -3,13 +3,12 @@ from __future__ import with_statement +import os import threading import traceback from Queue import Queue from copy import copy -from os import listdir, stat -from os.path import join from pprint import pformat from sys import exc_info, exc_clear from time import sleep, time, strftime, gmtime @@ -45,10 +44,10 @@ class PluginThread(threading.Thread): zip = zipfile.ZipFile(dump_name, "w") - for f in listdir(join("tmp", pyfile.pluginname)): + for f in os.listdir(os.path.join("tmp", pyfile.pluginname)): try: # avoid encoding errors - zip.write(join("tmp", pyfile.pluginname, f), fs_join(pyfile.pluginname, f)) + zip.write(os.path.join("tmp", pyfile.pluginname, f), fs_join(pyfile.pluginname, f)) except Exception: pass @@ -58,7 +57,7 @@ class PluginThread(threading.Thread): zip.writestr(info, dump) zip.close() - if not stat(dump_name).st_size: + if not os.stat(dump_name).st_size: raise Exception("Empty Zipfile") except Exception, e: diff --git a/pyload/api/__init__.py b/pyload/api/__init__.py index c17a1a66d..9fd0735d2 100644 --- a/pyload/api/__init__.py +++ b/pyload/api/__init__.py @@ -3,12 +3,12 @@ from __future__ import with_statement -from base64 import standard_b64encode -from os.path import join -from time import time +import os import re +import urlparse -from urlparse import urlparse +from base64 import standard_b64encode +from time import time from pyload.Datatype import PyFile from pyload.utils.packagetools import parseNames @@ -265,7 +265,7 @@ class Api(Iface): :param offset: line offset :return: List of log entries """ - filename = join(self.core.config.get("log", "log_folder"), 'log.txt') + filename = os.path.join(self.core.config.get("log", "log_folder"), 'log.txt') try: with open(filename, "r") as fh: lines = fh.readlines() @@ -326,7 +326,7 @@ class Api(Iface): :return: package id of the new package """ if self.core.config.get("general", "folder_per_package"): - folder = urlparse(name).path.split("/")[-1] + folder = urlparse.urlparse(name).path.split("/")[-1] else: folder = "" @@ -410,7 +410,7 @@ class Api(Iface): :param data: file content :return: online check """ - with open(join(self.core.config.get("general", "download_folder"), "tmp_" + container), "wb") as th: + with open(os.path.join(self.core.config.get("general", "download_folder"), "tmp_" + container), "wb") as th: th.write(str(data)) return self.checkOnlineStatus(urls + [th.name]) @@ -707,7 +707,7 @@ class Api(Iface): :param filename: filename, extension is important so it can correctly decrypted :param data: file content """ - with open(join(self.core.config.get("general", "download_folder"), "tmp_" + filename), "wb") as th: + with open(os.path.join(self.core.config.get("general", "download_folder"), "tmp_" + filename), "wb") as th: th.write(str(data)) self.addPackage(th.name, [th.name], Destination.Queue) diff --git a/pyload/config/Parser.py b/pyload/config/Parser.py index d74238007..6cd998024 100644 --- a/pyload/config/Parser.py +++ b/pyload/config/Parser.py @@ -2,10 +2,10 @@ from __future__ import with_statement +import os import shutil import traceback -from os.path import exists, join from time import sleep from pyload.utils import chmod, encode, decode @@ -49,10 +49,10 @@ class ConfigParser(object): def checkVersion(self, n=0): """determines if config need to be copied""" try: - if not exists("pyload.conf"): - shutil.copy(join(pypath, "pyload", "config", "default.conf"), "pyload.conf") + if not os.path.exists("pyload.conf"): + shutil.copy(os.path.join(pypath, "pyload", "config", "default.conf"), "pyload.conf") - if not exists("plugin.conf"): + if not os.path.exists("plugin.conf"): with open("plugin.conf", "wb") as f: f.write("version: " + str(CONF_VERSION)) @@ -61,7 +61,7 @@ class ConfigParser(object): v = v[v.find(":") + 1:].strip() if not v or int(v) < CONF_VERSION: - shutil.copy(join(pypath, "pyload", "config", "default.conf"), "pyload.conf") + shutil.copy(os.path.join(pypath, "pyload", "config", "default.conf"), "pyload.conf") print "Old version of config was replaced" with open("plugin.conf", "rb") as f: @@ -82,7 +82,7 @@ class ConfigParser(object): def readConfig(self): """reads the config file""" - self.config = self.parseConfig(join(pypath, "pyload", "config", "default.conf")) + self.config = self.parseConfig(os.path.join(pypath, "pyload", "config", "default.conf")) self.plugin = self.parseConfig("plugin.conf") try: @@ -206,7 +206,7 @@ class ConfigParser(object): def saveConfig(self, config, filename): """saves config to filename""" with open(filename, "wb") as f: - chmod(filename, 0600) + os.chmod(filename, 0600) f.write("version: %i \n" % CONF_VERSION) for section in config.iterkeys(): f.write('\n%s - "%s":\n' % (section, config[section]['desc'])) diff --git a/pyload/config/Setup.py b/pyload/config/Setup.py index 2143632c2..7e3fbffec 100644 --- a/pyload/config/Setup.py +++ b/pyload/config/Setup.py @@ -4,12 +4,10 @@ from __future__ import with_statement import __builtin__ - import os import sys from getpass import getpass -from os import chdir, makedirs, path from subprocess import PIPE, call from pyload.network.JsEngine import JsEngine @@ -424,14 +422,14 @@ class SetupAssistant(object): dirname = path.abspath(configdir) try: if not path.exists(dirname): - makedirs(dirname, 0700) + os.makedirs(dirname, 0700) - chdir(dirname) + os.chdir(dirname) if persistent: c = path.join(rootdir, "config", "configdir") if not path.exists(c): - makedirs(c, 0700) + os.makedirs(c, 0700) with open(c, "wb") as f: f.write(dirname) diff --git a/pyload/database/Backend.py b/pyload/database/Backend.py index 3262e6155..0fc961973 100644 --- a/pyload/database/Backend.py +++ b/pyload/database/Backend.py @@ -13,8 +13,6 @@ import threading import traceback from Queue import Queue -from os import remove -from os.path import exists from pyload.utils import chmod @@ -83,12 +81,12 @@ class DatabaseJob(object): def __repr__(self): - from os.path import basename + import os frame = self.frame.f_back output = "" for _i in xrange(5): - output += "\t%s:%s, %s\n" % (basename(frame.f_code.co_filename), frame.f_lineno, frame.f_code.co_name) + output += "\t%s:%s, %s\n" % (os.path.basename(frame.f_code.co_filename), frame.f_lineno, frame.f_code.co_name) frame = frame.f_back del frame del self.frame @@ -141,7 +139,7 @@ class DatabaseBackend(threading.Thread): convert = self._checkVersion() #: returns None or current version self.conn = sqlite3.connect("files.db") - chmod("files.db", 0600) + os.chmod("files.db", 0600) self.c = self.conn.cursor() #: compatibility @@ -172,7 +170,7 @@ class DatabaseBackend(threading.Thread): def _checkVersion(self): """ check db version and delete it if needed""" - if not exists("files.version"): + if not os.path.exists("files.version"): with open("files.version", "wb") as f: f.write(str(DB_VERSION)) return @@ -263,7 +261,7 @@ class DatabaseBackend(threading.Thread): def _migrateUser(self): - if exists("pyload.db"): + if os.path.exists("pyload.db"): try: self.core.log.info(_("Converting old Django DB")) except Exception: diff --git a/pyload/manager/Account.py b/pyload/manager/Account.py index ad770a1a8..b743ccabc 100644 --- a/pyload/manager/Account.py +++ b/pyload/manager/Account.py @@ -2,11 +2,10 @@ from __future__ import with_statement +import os import shutil import threading -from os.path import exists - from pyload.manager.Event import AccountUpdateEvent from pyload.utils import chmod, lock @@ -133,7 +132,7 @@ class AccountManager(object): for option, values in data['options'].iteritems(): f.write("\t@%s %s\n" % (option, " ".join(values))) - chmod(f.name, 0600) + os.chmod(f.name, 0600) except Exception, e: self.core.log.error(str(e)) diff --git a/pyload/manager/Plugin.py b/pyload/manager/Plugin.py index 0efd238b6..19898069c 100644 --- a/pyload/manager/Plugin.py +++ b/pyload/manager/Plugin.py @@ -2,13 +2,12 @@ from __future__ import with_statement +import os import re import sys import traceback from itertools import chain -from os import listdir, makedirs -from os.path import isdir, isfile, join, exists, abspath from sys import version_info from urllib import unquote @@ -37,11 +36,11 @@ class PluginManager(object): def loadTypes(self): - rootdir = join(pypath, "pyload", "plugin") + rootdir = os.path.join(pypath, "pyload", "plugin") userdir = "userplugins" - types = set().union(*[[d for d in listdir(p) if isdir(join(p, d))] - for p in (rootdir, userdir) if exists(p)]) + types = set().union(*[[d for d in os.listdir(p) if os.path.isdir(os.path.join(p, d))] + for p in (rootdir, userdir) if os.path.exists(p)]) if not types: self.core.log.critical(_("No plugins found!")) @@ -52,7 +51,7 @@ class PluginManager(object): def createIndex(self): """create information for all plugins available""" - sys.path.append(abspath("")) + sys.path.append(os.path.abspath("")) self.loadTypes() @@ -78,13 +77,13 @@ class PluginManager(object): if rootplugins: try: - pfolder = join("userplugins", folder) - if not exists(pfolder): - makedirs(pfolder) + pfolder = os.path.join("userplugins", folder) + if not os.path.exists(pfolder): + os.makedirs(pfolder) - for ifile in (join("userplugins", "__init__.py"), - join(pfolder, "__init__.py")): - if not exists(ifile): + for ifile in (os.path.join("userplugins", "__init__.py"), + os.path.join(pfolder, "__init__.py")): + if not os.path.exists(ifile): f = open(ifile, "wb") f.close() @@ -93,13 +92,13 @@ class PluginManager(object): return rootplugins else: - pfolder = join(pypath, "pyload", "plugin", folder) + pfolder = os.path.join(pypath, "pyload", "plugin", folder) - for f in listdir(pfolder): - if isfile(join(pfolder, f)) and f.endswith(".py") and not f.startswith("_"): + for f in os.listdir(pfolder): + if os.path.isfile(os.path.join(pfolder, f)) and f.endswith(".py") and not f.startswith("_"): try: - with open(join(pfolder, f)) as data: + with open(os.path.join(pfolder, f)) as data: content = data.read() except IOError, e: @@ -111,7 +110,7 @@ class PluginManager(object): name = name[:-4] if not re.search("class\\s+%s\\(" % name, content): - self.core.log.error(_("invalid classname: %s ignored") % join(pfolder, f)) + self.core.log.error(_("invalid classname: %s ignored") % os.path.join(pfolder, f)) version = self.VERSION.findall(content) if version: diff --git a/pyload/manager/Thread.py b/pyload/manager/Thread.py index 6df8ab622..abc7b2fef 100644 --- a/pyload/manager/Thread.py +++ b/pyload/manager/Thread.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- # @author: RaNaN +import os import random import re import threading @@ -8,7 +9,6 @@ import traceback import pycurl -from os.path import exists, join from random import choice from subprocess import Popen from time import sleep, time @@ -158,9 +158,9 @@ class ThreadManager(object): if not (0 < active.count(True) == len(active)): return False - if not exists(self.core.config.get("reconnect", "method")): - if exists(join(pypath, self.core.config.get("reconnect", "method"))): - self.core.config.set("reconnect", "method", join(pypath, self.core.config.get("reconnect", "method"))) + if not os.path.exists(self.core.config.get("reconnect", "method")): + if os.path.exists(os.path.join(pypath, self.core.config.get("reconnect", "method"))): + self.core.config.set("reconnect", "method", os.path.join(pypath, self.core.config.get("reconnect", "method"))) else: self.core.config.set("reconnect", "activated", False) self.core.log.warning(_("Reconnect script not found!")) diff --git a/pyload/network/HTTPChunk.py b/pyload/network/HTTPChunk.py index 85c20d519..a48c69cba 100644 --- a/pyload/network/HTTPChunk.py +++ b/pyload/network/HTTPChunk.py @@ -1,16 +1,17 @@ # -*- coding: utf-8 -*- # @author: RaNaN -from os import remove, stat, fsync -from os.path import exists -from time import sleep -from re import search -from pyload.utils import fs_encode import codecs -import pycurl +import os import urllib +import pycurl + +from time import sleep +from re import search + from pyload.network.HTTPRequest import HTTPRequest +from pyload.utils import fs_encode class WrongFormat(Exception): @@ -71,7 +72,7 @@ class ChunkInfo(object): @staticmethod def load(name): fs_name = fs_encode("%s.chunks" % name) - if not exists(fs_name): + if not os.path.exists(fs_name): raise IOError() fh = codecs.open(fs_name, "r", "utf_8") name = fh.readline()[:-1] @@ -101,9 +102,9 @@ class ChunkInfo(object): return ci - def remove(self): + def os.remove(self): fs_name = fs_encode("%s.chunks" % self.name) - if exists(fs_name): remove(fs_name) + if os.path.exists(fs_name): os.remove(fs_name) def getCount(self): @@ -172,7 +173,7 @@ class HTTPChunk(HTTPRequest): self.fp = open(fs_name, "ab") self.arrived = self.fp.tell() if not self.arrived: - self.arrived = stat(fs_name).st_size + self.arrived = os.stat(fs_name).st_size if self.range: # do nothing if chunk already finished @@ -301,11 +302,11 @@ class HTTPChunk(HTTPRequest): def flushFile(self): """ flush and close file """ self.fp.flush() - fsync(self.fp.fileno()) #: make sure everything was written to disk + os.fsync(self.fp.fileno()) #: make sure everything was written to disk self.fp.close() #: needs to be closed, or merging chunks will fail - def close(self): + def os.close(self): """ closes everything, unusable after this """ if self.fp: self.fp.close() self.c.close() diff --git a/pyload/network/HTTPDownload.py b/pyload/network/HTTPDownload.py index 62cef457b..78e069f7e 100644 --- a/pyload/network/HTTPDownload.py +++ b/pyload/network/HTTPDownload.py @@ -3,18 +3,16 @@ from __future__ import with_statement +import os import shutil import pycurl -from os import remove, fsync -from os.path import dirname from time import sleep, time from logging import getLogger from pyload.network.HTTPChunk import ChunkInfo, HTTPChunk from pyload.network.HTTPRequest import BadHeader - from pyload.plugin.Plugin import Abort from pyload.utils import fs_join, fs_encode @@ -101,7 +99,7 @@ class HTTPDownload(object): reshutil.move(fname) #: remove chunk if self.nameDisposition and self.disposition: - self.filename = fs_join(dirname(self.filename), self.nameDisposition) + self.filename = fs_join(os.path.dirname(self.filename), self.nameDisposition) shutil.move(init, fs_encode(self.filename)) self.info.remove() #: remove info file @@ -307,7 +305,7 @@ class HTTPDownload(object): chunk.close() - def close(self): + def os.close(self): """ cleanup """ for chunk in self.chunks: self.closeChunk(chunk) diff --git a/pyload/network/JsEngine.py b/pyload/network/JsEngine.py index b59d07dc4..c542b4dac 100644 --- a/pyload/network/JsEngine.py +++ b/pyload/network/JsEngine.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # @author: vuolter +import os import subprocess import sys -from os import path from urllib import quote from pyload.utils import encode, decode, uniqify diff --git a/pyload/network/XDCCRequest.py b/pyload/network/XDCCRequest.py index 24146ccaa..b9e9958aa 100644 --- a/pyload/network/XDCCRequest.py +++ b/pyload/network/XDCCRequest.py @@ -1,11 +1,10 @@ # -*- coding: utf-8 -*- # @author: jeix +import os import socket import struct -from os import remove -from os.path import exists from select import select from time import time @@ -57,14 +56,14 @@ class XDCCRequest(object): dccsock.settimeout(self.timeout) dccsock.connect((ip, port)) - if exists(filename): + if os.path.exists(filename): i = 0 nameParts = filename.rpartition(".") while True: newfilename = "%s-%d%s%s" % (nameParts[0], i, nameParts[1], nameParts[2]) i += 1 - if not exists(newfilename): + if not os.path.exists(newfilename): filename = newfilename break @@ -75,7 +74,7 @@ class XDCCRequest(object): if self.abort: dccsock.close() fh.close() - remove(filename) + os.remove(filename) raise Abort self._keepAlive(irc, ircbuffer) @@ -145,5 +144,5 @@ class XDCCRequest(object): return (self.recv * 100) / self.filesize if elf.filesize else 0 - def close(self): + def os.close(self): pass diff --git a/pyload/plugin/Container.py b/pyload/plugin/Container.py index 24fbf3738..5d7a99eac 100644 --- a/pyload/plugin/Container.py +++ b/pyload/plugin/Container.py @@ -2,11 +2,9 @@ from __future__ import with_statement +import os import re -from os import remove -from os.path import basename, exists - from pyload.plugin.Crypter import Crypter from pyload.utils import fs_join @@ -53,9 +51,9 @@ class Container(Crypter): self.fail(str(e)) else: - self.pyfile.name = basename(self.pyfile.url) - if not exists(self.pyfile.url): - if exists(fs_join(pypath, self.pyfile.url)): + self.pyfile.name = os.path.basename(self.pyfile.url) + if not os.path.exists(self.pyfile.url): + if os.path.exists(fs_join(pypath, self.pyfile.url)): self.pyfile.url = fs_join(pypath, self.pyfile.url) else: self.fail(_("File not exists")) @@ -63,4 +61,4 @@ class Container(Crypter): def deleteTmp(self): if self.pyfile.name.startswith("tmp_"): - remove(self.pyfile.url) + os.remove(self.pyfile.url) diff --git a/pyload/plugin/Plugin.py b/pyload/plugin/Plugin.py index 26590c9da..7eeec996f 100644 --- a/pyload/plugin/Plugin.py +++ b/pyload/plugin/Plugin.py @@ -12,11 +12,8 @@ import urllib import urlparse from itertools import islice -from os import remove, makedirs, chmod, stat -from os.path import exists, join if os.name != "nt": - from os import chown from pwd import getpwnam from grp import getgrnam @@ -468,7 +465,7 @@ class Plugin(Base): id = ("%.2f" % time.time())[-6:].replace(".", "") - with open(join("tmp", "tmpCaptcha_%s_%s.%s" % (self.getClassName(), id, imgtype)), "wb") as tmpCaptcha: + with open(os.path.join("tmp", "tmpCaptcha_%s_%s.%s" % (self.getClassName(), id, imgtype)), "wb") as tmpCaptcha: tmpCaptcha.write(img) has_plugin = self.getClassName() in self.core.pluginManager.ocrPlugins @@ -511,7 +508,7 @@ class Plugin(Base): if not self.core.debug: try: - remove(tmpCaptcha.name) + os.remove(tmpCaptcha.name) except Exception: pass @@ -554,8 +551,8 @@ class Plugin(Base): frame = currentframe() framefile = fs_join("tmp", self.getClassName(), "%s_line%s.dump.html" % (frame.f_back.f_code.co_name, frame.f_back.f_lineno)) try: - if not exists(join("tmp", self.getClassName())): - makedirs(join("tmp", self.getClassName())) + if not os.path.exists(os.path.join("tmp", self.getClassName())): + os.makedirs(os.path.join("tmp", self.getClassName())) with open(framefile, "wb") as f: del frame #: delete the frame or it wont be cleaned @@ -621,14 +618,14 @@ class Plugin(Base): location = fs_join(download_folder, self.pyfile.package().folder) - if not exists(location): + if not os.path.exists(location): try: - makedirs(location, int(self.core.config.get("permission", "folder"), 8)) + os.makedirs(location, int(self.core.config.get("permission", "folder"), 8)) if self.core.config.get("permission", "change_dl") and os.name != "nt": uid = getpwnam(self.core.config.get("permission", "user"))[2] gid = getgrnam(self.core.config.get("permission", "group"))[2] - chown(location, uid, gid) + os.chown(location, uid, gid) except Exception, e: self.fail(e) @@ -637,7 +634,7 @@ class Plugin(Base): location = fs_decode(location) name = safe_filename(self.pyfile.name) - filename = join(location, name) + filename = os.path.join(location, name) self.core.addonManager.dispatchEvent("download-start", self.pyfile, url, filename) @@ -654,13 +651,13 @@ class Plugin(Base): if disposition and newname != name: self.logInfo(_("%(name)s saved as %(newname)s") % {"name": name, "newname": newname}) self.pyfile.name = newname - filename = join(location, newname) + filename = os.path.join(location, newname) fs_filename = fs_encode(filename) if self.core.config.get("permission", "change_file"): try: - chmod(fs_filename, int(self.core.config.get("permission", "file"), 8)) + os.chmod(fs_filename, int(self.core.config.get("permission", "file"), 8)) except Exception, e: self.logWarning(_("Setting file mode failed"), e) @@ -668,7 +665,7 @@ class Plugin(Base): try: uid = getpwnam(self.core.config.get("permission", "user"))[2] gid = getgrnam(self.core.config.get("permission", "group"))[2] - chown(fs_filename, uid, gid) + os.chown(fs_filename, uid, gid) except Exception, e: self.logWarning(_("Setting User and Group failed"), e) @@ -688,10 +685,10 @@ class Plugin(Base): :return: dictionary key of the first rule that matched """ lastDownload = fs_encode(self.lastDownload) - if not exists(lastDownload): + if not os.path.exists(lastDownload): return None - size = stat(lastDownload) + size = os.stat(lastDownload) size = size.st_size if api_size and api_size <= size: @@ -709,13 +706,13 @@ class Plugin(Base): if isinstance(rule, basestring): if rule in content: if delete: - remove(lastDownload) + os.remove(lastDownload) return name elif hasattr(rule, "search"): m = rule.search(content) if m: if delete: - remove(lastDownload) + os.remove(lastDownload) self.lastCheck = m return name @@ -747,14 +744,14 @@ class Plugin(Base): download_folder = self.core.config.get("general", "download_folder") location = fs_join(download_folder, pack.folder, self.pyfile.name) - if starting and self.core.config.get("download", "skip_existing") and exists(location): + if starting and self.core.config.get("download", "skip_existing") and os.path.exists(location): size = os.stat(location).st_size if size >= self.pyfile.size: raise SkipDownload("File exists") pyfile = self.core.db.findDuplicates(self.pyfile.id, self.pyfile.package().folder, self.pyfile.name) if pyfile: - if exists(location): + if os.path.exists(location): raise SkipDownload(pyfile[0]) self.logDebug("File %s not skipped, because it does not exists." % self.pyfile.name) diff --git a/pyload/remote/ThriftBackend.py b/pyload/remote/ThriftBackend.py index f71e264e2..9e0afda16 100644 --- a/pyload/remote/ThriftBackend.py +++ b/pyload/remote/ThriftBackend.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # @author: RaNaN, mkaay -from os.path import exists +import os from pyload.manager.Remote import BackendBase @@ -23,7 +23,7 @@ class ThriftBackend(BackendBase): cert = None if self.core.config.get("ssl", "activated"): - if exists(self.core.config.get("ssl", "cert")) and exists(self.core.config.get("ssl", "key")): + if os.path.exists(self.core.config.get("ssl", "cert")) and os.path.exists(self.core.config.get("ssl", "key")): self.core.log.info(_("Using SSL ThriftBackend")) key = self.core.config.get("ssl", "key") cert = self.core.config.get("ssl", "cert") diff --git a/pyload/utils/__init__.py b/pyload/utils/__init__.py index 5033780c0..ef30a0996 100644 --- a/pyload/utils/__init__.py +++ b/pyload/utils/__init__.py @@ -12,7 +12,6 @@ import time # from gettext import gettext import pylgettext as gettext from htmlentitydefs import name2codepoint -from os.path import join from string import maketrans from urllib import unquote @@ -26,7 +25,7 @@ json_loads = json.loads json_dumps = json.dumps -def chmod(*args): +def os.chmod(*args): try: os.chmod(*args) except Exception: @@ -79,7 +78,7 @@ def save_path(name): def fs_join(*args): """ joins a path, encoding aware """ - return fs_encode(join(*[x if type(x) == unicode else decode(x) for x in args])) + return fs_encode(os.path.join(*[x if type(x) == unicode else decode(x) for x in args])) #: Deprecated method @@ -257,12 +256,11 @@ def versiontuple(v): #: By kindall (http://stackoverflow.com/a/11887825) def load_translation(name, locale, default="en"): """ Load language and return its translation object or None """ - from os.path import join from traceback import print_exc try: gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) - translation = gettext.translation(name, join(pypath, "locale"), + translation = gettext.translation(name, os.path.join(pypath, "locale"), languages=[locale, default], fallback=True) except Exception: print_exc() diff --git a/pyload/webui/__init__.py b/pyload/webui/__init__.py index 665be763a..58d60b5cc 100644 --- a/pyload/webui/__init__.py +++ b/pyload/webui/__init__.py @@ -1,15 +1,12 @@ # -*- coding: utf-8 -*- # @author: RaNaN, vuolter +import os import sys import pyload.utils.pylgettext as gettext -import os -from os.path import join, abspath, dirname, exists -from os import makedirs - -THEME_DIR = abspath(join(dirname(__file__), "themes")) -PYLOAD_DIR = abspath(join(THEME_DIR, "..", "..", "..")) +THEME_DIR = os.path.abspath(os.path.join(dirname(__file__), "themes")) +PYLOAD_DIR = os.path.abspath(os.path.join(THEME_DIR, "..", "..", "..")) sys.path.append(PYLOAD_DIR) @@ -52,13 +49,13 @@ if PREFIX: DEBUG = config.get("general", "debug_mode") or "-d" in sys.argv or "--debug" in sys.argv bottle.debug(DEBUG) -cache = join("tmp", "jinja_cache") -if not exists(cache): - makedirs(cache) +cache = os.path.join("tmp", "jinja_cache") +if not os.path.exists(cache): + os.makedirs(cache) bcc = FileSystemBytecodeCache(cache, '%s.cache') -loader = FileSystemLoader([THEME_DIR, join(THEME_DIR, THEME)]) +loader = FileSystemLoader([THEME_DIR, os.path.join(THEME_DIR, THEME)]) env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'], trim_blocks=True, auto_reload=False, bytecode_cache=bcc) @@ -80,7 +77,7 @@ else: env.filters['url'] = lambda x: PREFIX + x if x.startswith("/") else x gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) -translation = gettext.translation("django", join(PYLOAD_DIR, "locale"), +translation = gettext.translation("django", os.path.join(PYLOAD_DIR, "locale"), languages=[config.get("general", "language"), "en"],fallback=True) translation.install(True) env.install_gettext_translations(translation) diff --git a/pyload/webui/app/cnl.py b/pyload/webui/app/cnl.py index 635d4030c..fb64cbc5c 100644 --- a/pyload/webui/app/cnl.py +++ b/pyload/webui/app/cnl.py @@ -2,8 +2,9 @@ from __future__ import with_statement -from os.path import join +import os import re + from urllib import unquote from base64 import standard_b64decode from binascii import unhexlify @@ -60,7 +61,7 @@ def addcrypted(): package = request.forms.get('referer', 'ClickNLoad Package') dlc = request.forms['crypted'].replace(" ", "+") - dlc_path = join(DL_ROOT, package.replace("/", "").replace("\\", "").replace(":", "") + ".dlc") + dlc_path = os.path.join(DL_ROOT, package.replace("/", "").replace("\\", "").replace(":", "") + ".dlc") with open(dlc_path, "wb") as dlc_file: dlc_file.write(dlc) diff --git a/pyload/webui/app/json.py b/pyload/webui/app/json.py index 400eba624..24952cc34 100644 --- a/pyload/webui/app/json.py +++ b/pyload/webui/app/json.py @@ -2,11 +2,10 @@ from __future__ import with_statement +import os import shutil import traceback -from os.path import join - from bottle import route, request, HTTPError from pyload.utils import decode, formatSize @@ -166,7 +165,7 @@ def add_package(): if not name or name == "New Package": name = f.name - fpath = join(PYLOAD.getConfigValue("general", "download_folder"), "tmp_" + f.filename) + fpath = os.path.join(PYLOAD.getConfigValue("general", "download_folder"), "tmp_" + f.filename) with open(fpath, 'wb') as destination: shutil.copyfileobj(f.file, destination) links.insert(0, fpath) diff --git a/pyload/webui/app/pyloadweb.py b/pyload/webui/app/pyloadweb.py index 7f2317bd1..8ce9f2f74 100644 --- a/pyload/webui/app/pyloadweb.py +++ b/pyload/webui/app/pyloadweb.py @@ -1,14 +1,12 @@ # -*- coding: utf-8 -*- # @author: RaNaN -from datetime import datetime -from operator import itemgetter, attrgetter - -import time import os import sys -from os import listdir -from os.path import isdir, isfile, join, abspath +import time + +from datetime import datetime +from operator import itemgetter, attrgetter from sys import getfilesystemencoding from urllib import unquote @@ -81,8 +79,8 @@ def error500(error): @route('/<theme>/<file:re:(.+/)?[^/]+\.min\.[^/]+>') def server_min(theme, file): - filename = join(THEME_DIR, THEME, theme, file) - if not isfile(filename): + filename = os.path.join(THEME_DIR, THEME, theme, file) + if not os.path.isfile(filename): file = file.replace(".min.", ".") if file.endswith(".js"): return server_js(theme, file) @@ -196,32 +194,32 @@ def collector(): def downloads(): root = PYLOAD.getConfigValue("general", "download_folder") - if not isdir(root): + if not os.path.isdir(root): return base([_('Download directory not found.')]) data = { 'folder': [], 'files': [] } - items = listdir(fs_encode(root)) + items = os.listdir(fs_encode(root)) for item in sorted([fs_decode(x) for x in items]): - if isdir(fs_join(root, item)): + if os.path.isdir(fs_join(root, item)): folder = { 'name': item, 'path': item, 'files': [] } - files = listdir(fs_join(root, item)) + files = os.listdir(fs_join(root, item)) for file in sorted([fs_decode(x) for x in files]): try: - if isfile(fs_join(root, item, file)): + if os.path.isfile(fs_join(root, item, file)): folder['files'].append(file) except Exception: pass data['folder'].append(folder) - elif isfile(join(root, item)): + elif os.path.isfile(os.path.join(root, item)): data['files'].append(item) return render_to_response('downloads.html', {'files': data}, [pre_processor]) @@ -302,7 +300,7 @@ def config(): @route('/filechooser/<file:path>') @route('/pathchooser/<path:path>') @login_required('STATUS') -def path(file="", path=""): +def os.path(file="", path=""): type = "file" if file else "folder" path = os.path.normpath(unquotepath(path)) @@ -320,7 +318,7 @@ def path(file="", path=""): cwd = os.path.abspath(path) abs = True else: - cwd = relpath(path) + cwd = os.relpath(path) else: cwd = os.getcwd() @@ -333,10 +331,10 @@ def path(file="", path=""): parentdir = os.path.dirname(cwd) if not abs: if os.path.abspath(cwd) == "/": - cwd = relpath(cwd) + cwd = os.relpath(cwd) else: - cwd = relpath(cwd) + os.path.sep - parentdir = relpath(parentdir) + os.path.sep + cwd = os.relpath(cwd) + os.path.sep + parentdir = os.relpath(parentdir) + os.path.sep if os.path.abspath(cwd) == "/": parentdir = "" @@ -351,17 +349,17 @@ def path(file="", path=""): for f in folders: try: f = f.decode(getfilesystemencoding()) - data = {'name': f, 'fullpath': join(cwd, f)} + data = {'name': f, 'fullpath': os.path.join(cwd, f)} data['sort'] = data['fullpath'].lower() - data['modified'] = datetime.fromtimestamp(int(os.path.getmtime(join(cwd, f)))) + data['modified'] = datetime.fromtimestamp(int(os.path.getmtime(os.path.join(cwd, f)))) data['ext'] = os.path.splitext(f)[1] except Exception: continue - data['type'] = 'dir' if os.path.isdir(join(cwd, f)) else 'file' + data['type'] = 'dir' if os.path.isdir(os.path.join(cwd, f)) else 'file' - if os.path.isfile(join(cwd, f)): - data['size'] = os.path.getsize(join(cwd, f)) + if os.path.isfile(os.path.join(cwd, f)): + data['size'] = os.path.getsize(os.path.join(cwd, f)) power = 0 while (data['size'] / 1024) > 0.3: @@ -520,8 +518,8 @@ def info(): data = {"python" : sys.version, "os" : " ".join((os.name, sys.platform) + extra), "version" : PYLOAD.getServerVersion(), - "folder" : abspath(PYLOAD_DIR), "config": abspath(""), - "download" : abspath(conf['general']['download_folder']['value']), + "folder" : os.path.abspath(PYLOAD_DIR), "config": os.path.abspath(""), + "download" : os.path.abspath(conf['general']['download_folder']['value']), "freespace": formatSize(PYLOAD.freeSpace()), "remote" : conf['remote']['port']['value'], "webif" : conf['webui']['port']['value'], diff --git a/pyload/webui/app/utils.py b/pyload/webui/app/utils.py index 2753b7feb..69682fe67 100644 --- a/pyload/webui/app/utils.py +++ b/pyload/webui/app/utils.py @@ -1,13 +1,12 @@ # -*- coding: utf-8 -*- # @author: RaNaN, vuolter -from os.path import join +import os from bottle import request, HTTPError, redirect, ServerAdapter -from pyload.webui import env, THEME - from pyload.api import has_permission, PERMS, ROLE +from pyload.webui import env, THEME def render_to_response(file, args={}, proc=[]): diff --git a/pyload/webui/filters.py b/pyload/webui/filters.py index e11944c94..9d4d47c04 100644 --- a/pyload/webui/filters.py +++ b/pyload/webui/filters.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- import os -from os.path import abspath, commonprefix, join quotechar = "::/" @@ -11,18 +10,18 @@ except Exception: from posixpath import curdir, sep, pardir - def relpath(path, start=curdir): + def os.relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") - start_list = abspath(start).split(sep) - path_list = abspath(path).split(sep) + start_list = os.path.abspath(start).split(sep) + path_list = os.path.abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. - i = len(commonprefix([start_list, path_list])) + i = len(os.path.commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list) - i) + path_list[i:] if not rel_list: return curdir - return join(*rel_list) + return os.path.join(*rel_list) def quotepath(path): @@ -52,7 +51,7 @@ def path_make_absolute(path): def path_make_relative(path): - p = relpath(path) + p = os.relpath(path) if p[-1] == os.path.sep: return p else: @@ -1,11 +1,11 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +import os import sys import pyload -from os import path from setuptools import setup |