In Google Colaboratory, I can install a new library using !pip install package-name. But when I open the notebook again tomorrow, I need to re-install it every time.
Is there a way to install a library permanently? No need to spend time installing every time to use?
Yes. You can install the library in Google Drive. Then add the path to sys.path.
import os, sys
from google.colab import drive
drive.mount('/content/drive')
nb_path = '/content/notebooks'
os.symlink('/content/drive/My Drive/Colab Notebooks', nb_path)
sys.path.insert(0,nb_path)
Then you can install a library, for example, jdc, and specify the target.
!pip install --target=$nb_path jdc
Later, when you run the notebook again, you can skip the !pip install line. You can just import jdc and use it. Here's an example notebook.
https://colab.research.google.com/drive/1KpMDi9CjImudrzXsyTDAuRjtbahzIVjq
BTW, I really like jdc's %%add_to. It makes working with a big class much easier.
If you want a no-authorization solution. You can use mounting with gcsfuse + service-account key embedded in your notebook. Like this:
# first install gcsfuse
%%capture
!echo "deb http://packages.cloud.google.com/apt gcsfuse-bionic main" > /etc/apt/sources.list.d/gcsfuse.list
!curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -
!apt update
!apt install gcsfuse
Then get your service account credential from google cloud console and embed it in the notebook
%%writefile /key.json
{
"type": "service_account",
"project_id": "kora-id",
"private_key_id": "xxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxxx==\n-----END PRIVATE KEY-----\n",
"client_email": "colab-7#kora-id.iam.gserviceaccount.com",
"client_id": "100380920993833371482",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/colab-7%40kora-id.iam.gserviceaccount.com"
}
Then set environment to look for this credential file
%env GOOGLE_APPLICATION_CREDENTIALS=/key.json
You must then create (or have it already) a gcs bucket. And mount it to a made-up directory.
!mkdir /content/my-bucket
!gcsfuse my-bucket /content/my-bucket
Then finally, install the library there. Like my above answer.
import sys
nb_path = '/content/my-bucket'
sys.path.insert(0, nb_path)
# Do this just once
!pip install --target=$nb_path jdc
You can now import jdc without !pip install it next time.
In case you need to install multiple libraries here is a snippet:
def install_library_to_drive(libraries_list):
""" Install library on gdrive. Run this only once. """
drive_path_root = 'path/to/mounted/drive/directory/where/you/will/install/libraries'
for lib in libraries_list:
drive_path_lib = drive_path_root + lib
!pip install -q $lib --target=$drive_path_lib
sys.path.insert(0, drive_path_lib)
def load_library_from_drive(libraries_list):
""" Technically, it just appends install dir to a sys.path """
drive_path_root = 'path/to/mounted/drive/directory/where/you/will/install/libraries'
for lib in libraries_list:
drive_path_lib = drive_path_root + lib
sys.path.insert(0, drive_path_lib)
libraries_list = ["torch", "jsonlines", "transformers"] # list your libraries
install_library_to_drive(libraries_list) # Run this just once
load_library_from_drive(libraries_list)
Related
My setup.py
import setuptools
import os, stat
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
python_requires='>3.7',
name='MyApp',
version='1.0.0',
description='MyApp',
long_description=long_description,
long_description_content_type='text/markdown',
packages=setuptools.find_packages(),
data_files=[
('MyApp/', ['MyAppScripts/my_script'])],
entry_points = { 'console_scripts':['my_script = MyApp.myapp:main'] }
)
My Package:
./README.md
./MyAppScripts
./MyAppScripts/my_script
./MyApp
./MyApp/__init__.py
./MyApp/myapp.py
./setup.py
Hello Everyone, I hope I find you well and happy.
I have created a python application and would like entry_point scripts to install into directory /usr/local/MyApp and NOT /usr/local/bin. So far I am unable to get this to work and wondered if there is a way to override the install location for the entry_point scripts only? Package files should live in the default location.
As a work around I have generated the entry_point scripts and placed them into my setup directory below MyAppScripts. Using 'data_files' they are then copied relative to '/usr/local' into '/usr/local/MyApp' at install time which is the overall aim, but this is a bit of a cludge and I'd really like those entry_point scripts to get generated and land in the correct spot at install time.
I tried unsuccessfully:
entry_points = { 'console_scripts':['MyApp/my_script = myapp.scripts.myapp:main'] }
I also tried numerous install options such as:
python3 -m pip install --install-option="--prefix=/usr/local/MyApp" dist/MyApp-1.0.0-py3-none-any.whl
WARNING: Disabling all use of wheels due to the use of --build-option / --global-option / --install-option.
Which didn't workout ( possibly because my build is a whl? )
My build command:
python3 setup.py bdist_wheel
Please excuse my ignorance around packging, it is something that I am only just getting to grips with.
To summarise I'd like to run pip install and end up with entry_point script:
/usr/local/MyApp/my_script
Is anyone able to provide any advice please?
Thank you.
Regards,
D
I have a project such as:
myproject
setup.py
-myproject
-package1
-package2
I am using a setup.py as:
NAME='myproject'
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
package_data={NAME: ['VERSION']},
install_requires=require(),
extras_require={},
include_package_data=True)
When I install (pip install -e .) this I can access the packages as import myproject.package1. However, I want to change this so I instead import it as import mynewname.package1. In the example above when changing NAME=mynewname and then installing, the packages become no longer visible, and import mynewname gives a ModuleNotFoundError.
I don't want to change the name of the project or structure, just the top level name under which the package is installed. Something like import mynewname.myproject.package1 would also work, but i'm unsure of how to do this.
Thanks
I am a beginner in python. I am using python 3.7 via anaconda. I have made certain modules that I want to re-use by importing them in python scripts. Is there a way to centrally store all my modules in one directory and import them when needed?
My actual python scripts may be in different project directories but I want the importable user-defined modules to be stored in a central directory.
Thanks
you can create a virtual environment for maintaining packages for a project.Create a requirement.txt file from virtulenv and installback when needed.
pip install virtualenv
you should activate virtual env before using it.
pip freeze > requirements.txt
pip install -r requirements.txt
Read about virtualenv here https://pypi.org/project/virtualenv/1.7.1.2/#:~:text=You%20can%20install%20virtualenv%20with,it%20with%20python%20virtualenv.py.
Relative import method for your modules:
change your working directory and import modules.
import os
os. chdir('your docs folder path')
from your_modules import *
from module2 import *
add your folder to sys path:
import sys
import os.path
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import yourmodule
While trying to use Monet/Python Loader function,we are getting the following error
pymonetdb.exceptions.OperationalError: 'pyapi.eval_loader' undefined in: pyapi.eval_loader(0x7f34f01f2c60:ptr, "{_emit.emit( { 'event_date': '2019-10-10', 'status': 1})};":str);
Followed the below steps for installation
Python installation steps:
We have installed python 3.6
1)yum install autoconf
2)yum install automake
3)yum install libtool
4)yum install openssl
5)yum install openssl-devel
6)yum install python-devel
7)Configured environment path settings for python
export PYTHONPATH=$PATH:/usr/local/lib/python3.6/site-packages
Monet installation steps:
1)git clone https://github.com/MonetDB/MonetDB.git
2)cd /MonetDB
3)./bootstrap
4)cd..
5)mkdir testdir
6)cd testdir
7)../MonetDB/configure --enable-pyintegration=yes
While configuring we get the following status enabled message as below
py3integration is enabled
8)make
9)make install
10)monetdbd create /path/to/mydbfarm
11)monetdbd start /path/to/mydbfarm
12)monet stop -a
13)monet set embedpy=true
14)monet start -a
13)Enabled numpy(*pip install numpy*)
Created a loader by using the below python script
import pymonetdb
import sys
import os
connection = pymonetdb.connect(username="admin", password="admin#123", hostname="ipaddress", database="test")
cursor = connection.cursor()
cursor.execute("CREATE LOADER myloader() LANGUAGE PYTHON {_emit.emit( { 'event_date': '2019-10-10', 'status': 1})};") #create loader
cursor.execute("COPY LOADER INTO store FROM myloader();") #append the row from loader to table
connection.commit()
While running the above script getting the following error
pymonetdb.exceptions.OperationalError: 'pyapi.eval_loader' undefined in: pyapi.eval_loader(0x7f34f01f2c60:ptr, "{_emit.emit( { 'event_date': '2019-10-10', 'status': 1})};":str);
Please, help us to fix this issue.
The likely reason is that you are mixing python 2 and 3.
yum install python3-devel python3-numpy
--enable-py3integration=yes
monetdb set embedpy3=true <database name>
Mind the 3.
Also mind monetdb vs monet.
And also that monetdb set ... needs a database name. You are setting parameters per database, not globally.
Say I have a simple program: (module being some module to import)
from os import system
try:
import module
except:
system('py -m pip install module')
import module
My problem is, the module that i need to install needs administrator privileges.
How do I launch py in administrator?
I have tried things like:
system('py',adminstrator), and stupid stuff like that hoping one of them to work, but to no avail.
Thanks!
You can follow the instructions here to create a sudo.cmd file, make it available in your system path, and then you can gain Administrator privileges in your Python script with:
system('sudo py -m pip install module')