Skip to content
This repository has been archived by the owner on Jan 13, 2024. It is now read-only.

Commit

Permalink
refactoring + consider wheel packages
Browse files Browse the repository at this point in the history
  • Loading branch information
sdpython committed Jan 21, 2015
1 parent 7d2fb7c commit ad13e56
Show file tree
Hide file tree
Showing 12 changed files with 289 additions and 232 deletions.
14 changes: 11 additions & 3 deletions _unittests/ut_install/test_download.py
Expand Up @@ -19,7 +19,7 @@
import pyquickhelper


from src.pymyinstall.installhelper.install_cmd import ModuleInstall
from src.pymyinstall.installhelper.module_install import ModuleInstall
from pyquickhelper import fLOG

class TestDownload (unittest.TestCase):
Expand All @@ -36,14 +36,22 @@ def test_install(self) :
for _ in os.listdir(os.path.join(temp,"jsdifflib-master")):
os.remove(os.path.join(os.path.join(temp,"jsdifflib-master"),_))


m = ModuleInstall("jsdifflib","github",gitrepo="cemerick", fLOG = fLOG)
files = m.download(temp_folder = temp, unzipFile=True)
assert len(files)>0
for _ in files: assert os.path.exists(_)

def test_install_mlpy(self) :
fLOG (__file__, self._testMethodName, OutputPrint = __name__ == "__main__")
fold = os.path.abspath(os.path.split(__file__)[0])
temp = os.path.join(fold,"temp_download_mlpy")
if not os.path.exists(temp) : os.mkdir(temp)
for _ in os.listdir(temp):
if os.path.isfile(os.path.join(temp,_)) :
os.remove(os.path.join(temp,_))

if sys.platform.startswith("win"):
m = ModuleInstall("mlpy", "exe", fLOG = fLOG)
m = ModuleInstall("mlpy", "wheel", fLOG = fLOG)
exe = m.download(temp_folder = temp)
assert os.path.exists(exe)

Expand Down
17 changes: 2 additions & 15 deletions _unittests/ut_install/test_download_pyqt.py
Expand Up @@ -19,7 +19,7 @@
import pyquickhelper


from src.pymyinstall.installhelper.install_cmd import ModuleInstall
from src.pymyinstall.installhelper.module_install import ModuleInstall
from pyquickhelper import fLOG

class TestDownloadPyQt (unittest.TestCase):
Expand All @@ -35,22 +35,9 @@ def test_install_pyqt(self) :

if sys.platform.startswith("win"):
fLOG("install", "pyqt")
m = ModuleInstall("PyQt", "exe", mname = "pyqt", fLOG = fLOG)
m = ModuleInstall("PyQt", "wheel", mname = "pyqt", fLOG = fLOG)
exe = m.download(temp_folder = temp, file_save = os.path.join(temp, "out_page.html"))
assert os.path.exists(exe)

def test_regex(self):
fLOG (__file__, self._testMethodName, OutputPrint = __name__ == "__main__")
fold = os.path.abspath(os.path.split(__file__)[0])
file = os.path.join(fold,"data","page.html")
with open(file,"r",encoding="utf8") as f : content = f.read()
reg = ModuleInstall.expKPageQt.replace("Py3.3",
"Py{0}.{1}".format(sys.version_info.major,sys.version_info.minor))
fLOG(reg)
reg = re.compile(reg)
find = reg.findall(content)
assert len(find) > 0
fLOG(find)

if __name__ == "__main__" :
unittest.main ()
3 changes: 2 additions & 1 deletion _unittests/ut_install/test_install.py
Expand Up @@ -20,7 +20,8 @@
import pyquickhelper


from src.pymyinstall.installhelper.install_cmd import run_cmd, ModuleInstall
from src.pymyinstall.installhelper.module_install import ModuleInstall
from src.pymyinstall.installhelper.install_cmd_helper import run_cmd
from pyquickhelper import fLOG

class TestInstall (unittest.TestCase):
Expand Down
3 changes: 2 additions & 1 deletion src/pymyinstall/__init__.py
Expand Up @@ -36,7 +36,8 @@ def check( log = False):
"""
return True

from .installhelper.install_cmd import run_cmd, ModuleInstall, unzip_files, add_shortcut_to_desktop_for_module
from .installhelper.install_cmd_helper import run_cmd, unzip_files, add_shortcut_to_desktop_for_module
from .installhelper.module_install import ModuleInstall
from .installhelper.install_custom import download_from_sourceforge, download_file, download_page
from .installhelper.install_manual import get_install_list, open_tool_on_browser
from .setuphelper.ipython_helper import setup_ipython, add_shortcut_to_desktop_for_ipython
Expand Down
199 changes: 199 additions & 0 deletions src/pymyinstall/installhelper/install_cmd_helper.py
@@ -0,0 +1,199 @@
# coding: latin-1
"""
@file
@brief Various function to install various python module from various location.
"""
import sys, re, platform, os, urllib, urllib.request, urllib.error, zipfile,time, subprocess, importlib, importlib.util



def python_version():
"""
retrieve the platform and version of this python
@return tuple, example: ("win32","32bit") or ("win32","64bit")
"""
return sys.platform, platform.architecture()[0]

def split_cmp_command(cmd, remove_quotes = True) :
"""
splits a command line
@param cmd command line
@param remove_quotes True by default
@return list
"""
if isinstance (cmd, str) :
spl = cmd.split()
res = []
for s in spl :
if len(res) == 0 :
res.append(s)
elif res[-1].startswith('"') and not res[-1].endswith('"') :
res[-1] += " " + s
else :
res.append(s)
if remove_quotes :
res = [ _.strip('"') for _ in res ]
return res
else :
return cmd

def run_cmd ( cmd,
sin = "",
shell = False,
wait = False,
log_error = True,
secure = None,
stop_waiting_if = None,
do_not_log = False,
encerror = "ignore",
encoding = "utf8",
fLOG = print) :
"""
run a command line and wait for the result
@param cmd command line
@param sin sin, what must be written on the standard input
@param shell if True, cmd is a shell command (and no command window is opened)
@param wait call proc.wait
@param log_error if log_error, call fLOG (error)
@param secure if secure is a string (a valid filename), the function stores the output in a file
and reads it continuously
@param stop_waiting_if the function stops waiting if some condition is fulfilled.
The function received the last line from the logs.
@param do_not_log do not log the output
@param encerror encoding errors (ignore by default) while converting the output into a string
@param encoding encoding of the output
@param fLOG logging function
@return content of stdout, stderr (only if wait is True)
"""
if sin is not None and sin != "" :
raise NotImplementedError("sin is not used")

if secure is not None :
if not do_not_log :
fLOG("secure=",secure)
with open(secure,"w") as f : f.write("")
add = ">%s" % secure
if isinstance (cmd, str) : cmd += " " + add
else : cmd.append(add)
if not do_not_log :
fLOG ("execute ", cmd)

if sys.platform.startswith("win") :

startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

proc = subprocess.Popen (cmd,
shell = shell,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
startupinfo = startupinfo)
else :
proc = subprocess.Popen (split_cmp_command(cmd),
shell = shell,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
if wait :

out = [ ]
skip_waiting = False

if secure is None :
for line in proc.stdout :
if not do_not_log :
fLOG(line.decode(encoding, errors=encerror).strip("\n"))
try :
out.append(line.decode(encoding, errors=encerror).strip("\n"))
except UnicodeDecodeError as exu :
raise Exception("issue with cmd:" + str(cmd) + "\n" + str(exu))
if proc.stdout.closed:
break
if stop_waiting_if is not None and stop_waiting_if(line.decode("utf8", errors=encerror)) :
skip_waiting = True
break
else :
last = []
while proc.poll() is None :
if os.path.exists (secure) :
with open(secure,"r") as f :
lines = f.readlines()
if len(lines) > len(last) :
for line in lines[len(last):] :
if not do_not_log :
fLOG(line.strip("\n"))
out.append(line.strip("\n"))
last = lines
if stop_waiting_if is not None and len(last)>0 and stop_waiting_if(last[-1]) :
skip_waiting = True
break
time.sleep(0.1)

if not skip_waiting :
proc.wait ()

out = "\n".join(out)
err = proc.stderr.read().decode(encoding, errors=encerror)
if not do_not_log :
fLOG ("end of execution ", cmd)
if len (err) > 0 and log_error and not do_not_log :
fLOG ("error (log)\n%s" % err)
#return bytes.decode (out, errors="ignore"), bytes.decode(err, errors="ignore")
return out, err
else :
return "",""

def unzip_files(zipf, whereTo, fLOG = print):
"""
unzip files from a zip archive
@param zipf archive
@param whereTo destination folder
@param fLOG logging function
@return list of unzipped files
"""
file = zipfile.ZipFile (zipf, "r")
files = []
for info in file.infolist () :
if not os.path.exists (info.filename) :
data = file.read (info.filename)
tos = os.path.join (whereTo, info.filename)
if not os.path.exists (tos) :
finalfolder = os.path.split(tos)[0]
if not os.path.exists (finalfolder) :
fLOG (" creating folder ", finalfolder)
os.makedirs (finalfolder)
if not info.filename.endswith ("/") :
u = open (tos, "wb")
u.write ( data )
u.close()
files.append (tos)
fLOG (" unzipped ", info.filename, " to ", tos)
elif not tos.endswith("/") :
files.append (tos)
elif not info.filename.endswith ("/") :
files.append (info.filename)
return files

def add_shortcut_to_desktop_for_module(name):
"""
add a shortcut on a module which includes a script
@param name name of the module
@return shortcut was added or not
"""
if name == "spyder":
from .link_shortcuts import add_shortcut_to_desktop, suffix
md = ModuleInstall("spyder", "exe", script="spyder.bat")
sc = md.Script
if os.path.exists(sc):
ver = suffix()
r = add_shortcut_to_desktop(sc, name + "." + ver,name + "." + ver)
return os.path.exists(r)
else :
return False
else :
raise NotImplementedError("nothing implemented for module: {0}".format(name))
2 changes: 1 addition & 1 deletion src/pymyinstall/installhelper/install_custom.py
Expand Up @@ -5,7 +5,7 @@
"""
import os, urllib, urllib.error, urllib.request

from .install_cmd import ModuleInstall
from .module_install import ModuleInstall

def download_page(url):
"""
Expand Down
2 changes: 1 addition & 1 deletion src/pymyinstall/installhelper/install_custom_pandoc.py
Expand Up @@ -5,7 +5,7 @@
"""
import sys, re, os

from .install_cmd import run_cmd
from .install_cmd_helper import run_cmd
from .install_custom import download_page, download_file

def IsPandocInstalled():
Expand Down
2 changes: 1 addition & 1 deletion src/pymyinstall/installhelper/install_custom_scite.py
Expand Up @@ -5,7 +5,7 @@
"""
import sys, re, os

from .install_cmd import unzip_files
from .install_cmd_helper import unzip_files
from .install_custom import download_page, download_from_sourceforge
from .link_shortcuts import add_shortcut_to_desktop, suffix

Expand Down
2 changes: 1 addition & 1 deletion src/pymyinstall/installhelper/install_custom_sqlitespy.py
Expand Up @@ -5,7 +5,7 @@
"""
import sys, re, os

from .install_cmd import unzip_files
from .install_cmd_helper import unzip_files
from .link_shortcuts import add_shortcut_to_desktop
from .install_custom import download_page, download_from_sourceforge

Expand Down

0 comments on commit ad13e56

Please sign in to comment.