python Python.Modules.Packages.Libraries
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python.Modules.Packages.Libraries相关的知识,希望对你有一定的参考价值。
import sys
import matplotlib
import code128
import subprocess
import Crypto
#print(dir(code128))
# print(matplotlib.__version__)
# print(Crypto.__version__)
# for name, module in sorted(sys.modules.items()):
# #print(name, module)
# #print(module.__version__)
# if hasattr(module, '__version__'):
# print (name, module.__version__ )
def modulemethods(module_name, verbose="yes"):
'''
Author: p.doulgeridis
Name: modulemethods
Function: modulemethods(module_name, verbose="yes")
Input: * module_name as string ie 'numpy'
* verbose > [Y|N]
Output: List of all module name and attributes
Usage: * #modulemethods('code128')
* print(modulemethods('code128', verbose="no"))
Notes: Requires 'importlib'
'''
outlist = []
import importlib
module = importlib.import_module(module_name, package=None)
outlist = dir(module)
if verbose == "yes":
for j in outlist:
print(j)
return 0
else:
outlist = dir(module)
return outlist
#for j in dir(module_name):
# print(j)
#print(help(module))
def modulehelp(module_name):
'''
Author: p.doulgeridis
Name: modulehelp
Function: modulehelp(module_name)
Input: * module_name as string
Output: stdout -> help text
Usage: modulehelp('code128')
Notes: Requires 'importlib'
'''
import importlib
module = importlib.import_module(module_name, package=None)
print(help(module))
def moduleHasMethod(module_name, method_name):
'''
Author: p.doulgeridis
Name: moduleHasMethod
Function: moduleHasMethod(module_name, method_name)
Input: * module_name as string, ie 'code128'
* method_name as string, ie __name__
Output: [ T|F ]
Usage: print(moduleHasMethod('code128', '__name__'))
Usage: if moduleHasMethod('code128', '__name__'): ....
Notes: Requires 'importlib' module
'''
import importlib
module = importlib.import_module(module_name, package=None)
if hasattr(module, method_name):
return True
else:
return False
#modulemethods('matplotlib')
#modulemethods('code128')
print(modulemethods('code128', verbose="no"))
#modulehelp('code128')
print(moduleHasMethod('code128', '__name__'))
#######################################################
# WAYS TO IMPORT MODULES
#
#
#
# 1. CRITICAL MODULES
# - REQUIRE TERMINATION (WE NEED TO RAISE EXCEPTION)
# 2. NON CRITICAL MODULES
# - WARNING NOT TERMINATION
# 3. MASS DYNAMICLY IMPORT MODULES
# 4. TYPES OF EXCEPTIONS
#
#
########################################################
#############################################
# CRITICAL MODULES - 1 by one block
# ASSIGN NAME TO MODULE NAME
module_name = 'os'
print ("Importing module " + str(module_name))
try:
module_in = __import__(module_name)
globals()[module_name] = module_in
except ImportError:
raise ImportError("Import Error: Could not load module " + str(module_name))
else:
print ("Module: " + str(module_name) + " imported succesfully")
##############################################
# CRITICAL MODULES - IN LIST
critical_modules = [ 'os', 'sys', 'time', 'lxml' ]
for module in critical_modules:
try:
# because we want to import using a variable, do it this way
module_obj = __import__(module)
# create a global object containging our module
globals()[module] = module_obj
except ImportError:
sys.stderr.write("ERROR: missing python module: " + module + "\n")
sys.exit(1)
else:
print ("Module: " + str(module) + " loaded successfully")
################################################
# NON CRITICAL MODULES - 1
# ASSIGN NAME TO MODULE NAME
module_name = 'os'
print ("Importing module " + str(module_name))
try:
module_in = __import__(module_name)
globals()[module_name] = module_in
except ImportError:
print ("Import Error: Could not load module " + str(module_name))
else:
print ("Module: " + str(module_name) + " imported succesfully")
#################################################
# NON CRITICAL MODULES - MANY
critical_modules = [ 'os', 'sys', 'time', 'lxml' ]
for module in critical_modules:
try:
# because we want to import using a variable, do it this way
module_obj = __import__(module)
# create a global object containging our module
globals()[module] = module_obj
except ImportError:
print ("Import Error: Could not load module " + str(module))
else:
print ("Module: " + str(module) + " loaded successfully")
# Import modules
print ("Importing modules. Please wait...")
try:
import os
except ImportError:
raise ImportError("Import Error: Could not load module os")
else:
print ("Module os imported successfully")
print ("######")
libnames = [ 'os', 'sys', 'time' ]
for libname in libnames:
try:
lib = __import__(libname)
except:
print (sys.exc_info())
else:
print ("Module: " + str(lib) + "load success")
globals()[libname] = lib
os = os
sys = sys
time = time
#import sys
#import time
try:
import urllib.request
python3 = True
print ("Module urllib.request located...")
print ("Running in python3 version....\n")
except ImportError:
import urllib2
python3 = False
print ("Module urllib.request located...")
print ("Running in python3 version....\n")
# When importing modules, we can differentiate by severity:
# 1. Critical (execution needs to terminated, exception raised)
# 2. Non critical (execution can persist, but we still want to print a message)
#In case of critical modules, we can use:
try:
from _foo import *
except ImportError:
raise ImportError('<any message you want here>')
#In case of non critical modules, we can use:
#Here, we raise no importerror, so execution continues
try:
import sys
except:
print sys.exc_info()
#In case we want to case over non critical modules with iteration:
libnames = ['numpy', 'scipy', 'operator']
for libname in libnames:
try:
lib = __import__(libname)
except:
print sys.exc_info()
else:
globals()[libname] = lib
#You can either extend that to handle the import ... as ... and from ... import ...
#forms or just do the assignments later manually, ie.:
#np = numpy
#sp = scipy
#itemgetter = operator.itemgetter
# Using Python package manager to check if a library is available
# GOOD
import pkg_resources
try:
pkg_resources.get_distribution('plone.dexterity')
except pkg_resources.DistributionNotFound:
HAS_DEXTERITY = False
else:
HAS_DEXTERITY = True
#More about the topic can be found here http://developer.plone.org/reference_manuals/external/plone.api/contribute/conventions.html#about-imports
#As the comments above point out, Python standard library modules (stdlib) are always available UNLESS you run Python in an embedded environment with stripped down run-time.
#Managing environments :
#Environments are like different sets of environmental variables
#and or packages and python versions installed
#so we can shift through different environments. Ie :
#
# a. Environment A ( py 2.7, specific packages, specific environmental variables)
# b. Environment B ( py 3.1, specific packages, specific environmental variables)
#
################################################################################
# This is how to activate/deactivate python environments in a batch file.
call activate test1
python -V
python %SCRIPT_DIR%MergingXml4.py %DIR_IN%
if errorlevel 1 (
CALL:error10 "136" "Merging Script Fail. Check Python Version."
GOTO :EOF
)
python -V
call deactivate
python -V
pause
################################################################################
# getting help
conda env --help
#Create environments
conda create --name snowflakes biopython
# Create environment with specific python version
conda create --name python2.7 python=2.7.9
#See all environments
conda info --envs
#Which environment are we using? - look for asterisk
conda info --envs
#Clone an environment
onda create --name flowers --clone snowflakes
#Remove an environment
conda remove --name flowers --all
#Activate environment
activate workppc
#Deactivate environment
#See all installed packages - for active environment
conda list --explicit
#Search for packages
anaconda search -t conda ping
#Create a copy of another developer’s environment from their environment.yml file:
conda env create -f environment.yml
#Build identical conda environments
conda list --explicit
#Create a file containing this spec list in the current working directory.
#You may use the filename spec-file.txt or any other filename.
conda list --explicit > spec-file.txt
#As the comment at the top of the file explains, the command
#conda create --name MyEnvironment --file spec-file.txt
#uses the spec file to create an identical environment on the same machine or another machine.
#Adds these packages to an existing environment.
conda install --name MyEnvironment --file spec-file.txt adds
#How to set enviromental variables
#Saved environment variables
#Conda environments can include saved environment variables on Linux, macOS, and Windows.
#Suppose you want an environment ‘analytics’ to store a secret key needed to log in to a server and a
#path to a configuration file. We will write a script named env_vars to do this.
#Linux and macOS
#Locate the directory for the conda environment, such as /home/jsmith/anaconda3/envs/analytics . Enter that directory and create these subdirectories and files:
cd /home/jsmith/anaconda3/envs/analytics
mkdir -p ./etc/conda/activate.d
mkdir -p ./etc/conda/deactivate.d
touch ./etc/conda/activate.d/env_vars.sh
touch ./etc/conda/deactivate.d/env_vars.sh
#Edit the two files. ./etc/conda/activate.d/env_vars.sh should have this:
#!/bin/sh
export MY_KEY='secret-key-value'
export MY_FILE=/path/to/my/file/
#And ./etc/conda/deactivate.d/env_vars.sh should have this:
#!/bin/sh
unset MY_KEY
unset MY_FILE
#Now when you use source activate analytics the environment variables MY_KEY and MY_FILE will be
#set to the values you wrote into the file, and when you use source deactivate those variables will be erased.
#Windows
#Locate the directory for the conda environment, such as C:\Users\jsmith\Anaconda3\envs\analytics . Enter that directory and create these subdirectories and files:
cd C:\Users\jsmith\Anaconda3\envs\analytics
mkdir .\etc\conda\activate.d
mkdir .\etc\conda\deactivate.d
type NUL > .\etc\conda\activate.d\env_vars.bat
type NUL > .\etc\conda\deactivate.d\env_vars.bat
#Edit the two files. .\etc\conda\activate.d\env_vars.bat should have this:
set MY_KEY='secret-key-value'
set MY_FILE=C:\path\to\my\file
And .\etc\conda\deactivate.d\env_vars.bat should have this:
set MY_KEY=
set MY_FILE=
#Now when you use activate analytics the environment variables MY_KEY and MY_FILE will be set to the values you wrote into the file, and when you use deactivate those variables will be erased.
#More notes on environment variable scripts
#These script files can be part of a conda package, in which case
#these environment variables become active when an environment containing that package is activated.
#Scripts can be given any name, but multiple packages may create script files, so be sure
#that you choose descriptive names for your scripts that are not used by other packages.
#One popular option is to give the script a name of the form packagename-scriptname.sh (or on Windows packagename-scriptname.bat).
# Check python version
conda search python
# Install different python version
#let’s say you need Python 3 to learn programming, but you don’t want to wipe out your Python 2.7
#environment by updating Python. You can create and activate a
Linux, OS X: source activate snakes
Windows: activate snakes
#new environment named snakes, and install the latest version of Python 3 as follows:
conda create --name snakes python=3
#Check that snakes is added :
conda info --envs
# Get the python version
python --version
######################################################
#Create a Python 3.5 environment
#To create a new environment with a different version of Python,
#use the conda create command. In this example, we’ll make the new environment for Python 3.5:
$ conda create -n py35 python=3.5 anaconda
#Here, the ‘py35’ is the name of the environment you want to create,
#and ‘anaconda’ is the meta-package that includes all of the actual
#Python packages comprising the Anaconda distribution. When creating
#a new environment and installing Anaconda, you can specify the exact
#package and Python versions, for example, numpy=1.7 or python=3.5.
#######################################################
#Create a Python 2.7 environment
#In this example, we’ll make a new environment for Python 2.7:
$ conda create -n py27 python=2.7 anaconda
# It will include all standard packages installed with anaconda
########################################################
#Update or Upgrade Python
#If you are in an environment with Python version 3.4.2, this command will update Python to 3.4.3, which is the latest version in the 3.4 branch:
$ conda update python
#And this command will upgrade Python to another branch such as 3.5 by installing that version of Python:
$ conda install python=3.5
#Help :
conda --help
conda update --help
#GEt version :
conda --version
#Update conda:
conda update conda
#####################################################
#Using R with conda
#For Linux, OS X and Windows
#If you have conda installed, you can easily install the R programming language and over 80 of the most used R
#packages for data science with one command. Conda helps you keep your packages and dependencies up to date.
#You can also easily create and share your own custom R packages.
#R-Essentials works very much like Anaconda:
#Installs all of the most popular packages with all of their dependencies with one command:
conda install -c r r-essentials
#Update all of the packages and their dependencies with one command:
conda update -c r r-essentials
#Update a single package in R-Essentials (if a new version of the package is
#available in the R channel) with the command
conda update r-XXXX
#How to install “R Essentials”
#Download and install Anaconda
#Install the R Essentials package into the current environment:
conda install -c r r-essentials
#Create and share your own custom R bundle
#Building and sharing your own custom R bundles with others is like building and sharing conda packages.
#For example, create a simple custom R bundle meta-package named “Custom-R-Bundle” containing several popular
#programs and their dependencies with the command:
conda metapackage custom-r-bundle 0.1.0 --dependencies r-irkernel jupyter r-ggplot2 r-dplyr --summary "My custom R bundle"
#Now you can easily share your new meta-package with friends and colleagues by uploading it to your channel on Anaconda Cloud:
conda install anaconda-client
anaconda login
anaconda upload path/to/custom-r-bundle-0.1.0-0.tar.bz2
#Your friends and colleagues now have access to your Custom-R-Bundle from any computer with the command:
conda install -c <your anaconda.org username> custom-r-bundle
#For more information, see Christine Doig’s blog post Jupyter and conda for R language.
######################################################
# CONVERT PYTHON TO EXE
#
# Will install all required packages
# Everything will be stored in a directory ./dist
# which will contain the .exe
#
# The .exe can be ran from the command line normally
#
# Prerequisites:
# pyinstaller
# pefile
#
# Installation details on prerequisites
To install this package with conda run:
conda install -c acellera pyinstaller=3.2.3
#
To install this package with conda run:
conda install -c conda-forge pefile=2016.3.28
#
# Convert:
pyinstaller script.py
1. printmodules : Print all functions / methods in module
2. get_help : Manuals for functions / help
3. conda_help : Gives us help on the conda command
4. conda_env : Conda - Managing environments
5. conda_packages : Conda - Managing packages
6. conda_man_python : Conda - Managing Python
7. conda_install_r : Conda - Install r
8. convertpytoexe : Convert python script to executable
9. installwithpip : Install with pip from anywhere
#Managing Python
#Contents
#Managing Python
#Check Python versions
#Install a different version of Python
#Use a different version of Python
#Create Python 2 or 3 environments
#Create a Python 3.5 environment
#Create a Python 2.7 environment
#Update or Upgrade Python
#Conda treats Python the same as any other package, so it’s very easy to manage and update multiple installations.
#Check Python versions
#Check to see which versions of Python are available to install:
conda search python
#Install a different version of Python
#So now let’s say you need Python 3 to learn programming, but you don’t want to wipe out your Python 2.7
#environment by updating Python. You can create and activate a new environment named snakes, and install the latest version of Python 3 as follows:
conda create --name snakes python=3
Linux, OS X: source activate snakes
Windows: activate snakes
#TIP: It would be wise to name this environment a descriptive name like “python3” but that is not as much fun.
#To verify that the snakes environment has now been added, type the command:
conda info --envs
#Conda displays the list of all environments, with the current environment highlighted by a ‘*’.
#Verify that the snakes environment uses Python version 3:
python --version
#Use a different version of Python
#To switch to the new environment with a different version of Python, you simply need to activate it. Let’s switch back to 2.7:
Linux, OS X: source activate snowflakes
Windows: activate snowflakes
#Verify that the snowflakes environment uses Python version 2:
python --version
#After you are finished working in the snowflakes environment, to close it you
#can either deactivate it, or activate a new environment.
#Create Python 2 or 3 environments
#Anaconda supports Python 2.7, 3.4, and 3.5. The default is Python 2.7 or 3.5, depending on which
#installer you used. If the installer you used is Anaconda or Miniconda, the default is 2.7. If the installer you used is Anaconda3 or Miniconda3, the default is 3.5.
#Create a Python 3.5 environment
#To create a new environment with a different version of Python, use the conda
#create command. In this example, we’ll make the new environment for Python 3.5:
$ conda create -n py35 python=3.5 anaconda
#Here, the ‘py35’ is the name of the environment you want to create, and ‘anaconda’ is the meta-package that includes all of the actual Python packages comprising the Anaconda distribution. When creating a new environment and installing Anaconda, you can specify the exact package and Python versions, for example, numpy=1.7 or python=3.5.
#Create a Python 2.7 environment
#In this example, we’ll make a new environment for Python 2.7:
$ conda create -n py27 python=2.7 anaconda
#Update or Upgrade Python
#If you are in an environment with Python version 3.4.2, this command will update Python to 3.4.3, which is the latest version in the 3.4 branch:
$ conda update python
#And this command will upgrade Python to another branch such as 3.5 by installing that version of Python:
$ conda install python=3.5
# From the python terminal
ie. for the function complex()
help(complex)
? complex
ie. for the function len()
help(len)
? len
# Prints contents of a module
import math # Imports the math module
everything = dir(math) # Sets everything to a list of things from math
print (everything) # Prints 'em all!
#MANAGING PACKAGES :
#List all packages
#List all of your packages in the active environment:
conda list
#To list all of your packages installed into a non-active environment named snowflakes:
conda list -n snowflakes
#Search for a package
#To see if a specific package is available for conda to install:
conda search beautiful-soup
#This displays the package name, so we know it is available.
#Install a package
#Install a package such as “Beautiful Soup” into the current environment, using conda install as follows:
conda install --name bunnies beautiful-soup
#NOTE: If you do not specify the name of the environment where you want it installed (–name bunnies) it will install in the current environment.
#Activate the bunnies environment, and do a conda list to see the new program installed:
#Linux, OS X: source activate bunnies Windows:
activate bunnies
#All:
conda list
#NOTE: Installing a commercial package (such as IOPro) is the same as installing any other package: conda install --name bunnies iopro
#Install a package from Anaconda.org
#For packages that are not available using conda install, we can look in the
#repository Anaconda.org. Anaconda.org, formerly Binstar.org, is a package
#management service for both public and private package repositories. Anaconda.org
#is a Continuum Analytics product, just like Anaconda and Miniconda.
#In a browser, go to http://anaconda.org. To find the package named “bottleneck”
#enter that search term in the top left box named “Search Packages.”
#Find the package you want and click to go to the detail page. There you will see
#the name of the channel – in this case it is the “pandas” channel.
#Now that you know the channel name, you can use the conda install command to get it:
conda install -c pandas bottleneck
#That means “Conda install the Bottleneck package from the Pandas channel on Anaconda.org.”
#Check to see that the package is now installed:
conda list
#You will see a list of packages, including Bottleneck.
#NOTE: Conda can install packages from multiple channels.
#Install non-conda packages
#If a package is not available from conda or Anaconda.org, you may be able to find and install the package with another package manager like pip.
#NOTE: Both pip and conda are already included in Anaconda and Miniconda, so you do not need to install them separately.
#NOTE: Conda environments replace virtualenv so there’s no need to activate a virtualenv before using pip.
#Activate the environment where you want to put the program, then pip install a program named “See”:
Linux, OS X: source activate bunnies
Windows: activate bunnies
All: pip install see
#Check to see that the See package was installed by pip:
conda list
#Install a commercial package
#Installing commercial packages is the same as installing any other package with conda. So as an example, let’s install and then delete a free trial of one of Continuum’s commercial packages IOPro, which can speed up your Python processing:
conda install iopro
#TIP: Except for academic use, this free trial expires after 30 days.
#You can now install and verify any package you want using conda, whether using the conda command, downloading from Anaconda.org, or using pip install, and whether open source or commercial.
#Package update
#You can check to see if a new update is available with the conda update command. If conda tells you an update is available, you can then choose whether or not to install it.
#Use the conda update command to update a specific package:
conda update biopython
#You can use the conda update command to update conda itself:
conda update conda
#You can also update Python with the update command:
conda update python
#NOTE: Conda will update to the highest version in its series, so Python 2.7 will update to the highest available in the 2.x series, and 3.5 will update to the highest available in the 3.x series.
#Regardless of what package you are updating, conda will compare versions, then let you know what is available to install. If none are available, conda will reply “All requested packages are already installed.”
#If a newer version of your package is available, and you wish to update it, type Y to update:
Proceed ([y]/n)? y
#Type “y” for yes.
#Package remove
#If you decide not to continue using a package, for example, the commercial package IOPro, you can remove it from the bunnies environment with:
conda remove --name bunnies iopro
#Confirm that the package has been removed:
conda list
##########################################################################
# In case there's a problem with pip install :
###
#Do you happen to have the Perl pip lying around somewhere?
#Sounds like the problem described here:
https://github.com/mike-perdide/gitbuster/issues/62
#To check, in Windows command prompt execute:
C:\>where pip
#This will potentially output the following:
C:\strawberry\perl\bin\pip
C:\strawberry\perl\bin\pip.bat
#If so, this is your problem. Unistall Strawberry Perl or use the full path to python pip.
# Way to install modules without conda
# Installs in default environment
python -m pip install <module name>
# View installed packages
python -m pip list
以上是关于python Python.Modules.Packages.Libraries的主要内容,如果未能解决你的问题,请参考以下文章