1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
--- a/khinsider.py
+++ b/khinsider.py
@@ -35,89 +35,7 @@
sys.stderr = self._stderr
-# --- Install prerequisites ---
-# (This section in `if __name__ == '__main__':` is entirely unrelated to the
-# rest of the module, and doesn't even run if the module isn't run by itself.)
-
-if __name__ == '__main__':
- # To check for the existence of modules without importing them.
- # Apparently imp and importlib are a forest of deprecation!
- # The API was changed once in 3.3 (deprecating imp),
- # and then again in 3.4 (deprecating the 3.3 API).
- # So.... we have to do this dance to avoid deprecation warnings.
- try:
- try:
- from importlib.util import find_spec as find_module # Python 3.4+
- except ImportError:
- from importlib import find_loader as find_module # Python 3.3
- except ImportError:
- from imp import find_module # Python 2
-
- # User-friendly name, import name, pip specification.
- requiredModules = [
- ['requests', 'requests', 'requests >= 2.0.0, < 3.0.0'],
- ['Beautiful Soup 4', 'bs4', 'beautifulsoup4 >= 4.4.0, < 5.0.0']
- ]
-
- def moduleExists(name):
- try:
- result = find_module(name)
- except ImportError:
- return False
- else:
- return result is not None
- def neededInstalls(requiredModules=requiredModules):
- uninstalledModules = []
- for module in requiredModules:
- if not moduleExists(module[1]):
- uninstalledModules.append(module)
- return uninstalledModules
-
- def install(package):
- nowhere = open(os.devnull, 'w')
- exitStatus = subprocess.call([sys.executable, '-m', 'pip', 'install', package],
- stdout=nowhere,
- stderr=nowhere)
- if exitStatus != 0:
- raise OSError("Failed to install package.")
- def installModules(modules, verbose=True):
- for module in modules:
- if verbose:
- print("Installing {}...".format(module[0]))
-
- try:
- install(module[2])
- except OSError as e:
- if verbose:
- print("Failed to install {}. "
- "You may need to run the script as an administrator "
- "or superuser.".format(module[0]),
- file=sys.stderr)
- print("You can also try to install the package manually "
- "(pip install \"{}\")".format(module[2]),
- file=sys.stderr)
- raise e
- def installRequiredModules(needed=None, verbose=True):
- needed = neededInstalls() if needed is None else needed
- installModules(neededInstalls(), verbose)
-
- needed = neededInstalls()
- if needed:
- if moduleExists('pip'):
- # Needed to call pip the official way.
- import subprocess
- else:
- print("You don't seem to have pip installed!", file=sys.stderr)
- print("Get it from https://pip.readthedocs.org/en/latest/installing.html", file=sys.stderr)
- sys.exit(1)
-
- try:
- installRequiredModules(needed)
- except OSError:
- sys.exit(1)
-
-# ------
import requests
from bs4 import BeautifulSoup
|