python 本地安装库_(Python)在本地使用库而不是安装它

博主编写了一个使用tweepy库发推文的Python脚本,但在无安装权限的服务器上运行遇到问题。介绍了不安装库使用它的方法,如使用VirtualEnv、按用户安装模块、设置工作目录、添加PYTHONPATH环境变量、编辑sys.path等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Script:

I've written a script in python that occasionally sends tweets to twitter

It only uses one library called: tweepy

after installing the library it works, great.

Problem:

I would like to host the script on a server where I do not have privileges to install anything

It would be great if I can just include it locally from the folder I've got it in.

As of right now, all I need to include at the top of my file is:

import tweepy

the tweepy folder (DOES have a __init__.py file which I believe is important.

Question:

How can I use this library without installing it?

basically I want to replace: import tweepy with import local_folder/tweepy/*

this might just be python common sense, but I'm stuck!

解决方案

EDIT: This answer is outdated. You should be using VirtualEnv. If you are allergic to third-party software for some reason (in which case, why are you installing libraries?), there is something called venv, that is literally built into python3, so there is no excuse not to use some kind of virtualization. (Most people active in the community prefer VirtualEnv, however. See https://stackoverflow.com/a/41573588/410889.)

VirtualEnv installs a local python interpreter, with a local packages folder and everything. In addition to this entirely solving the issue of administrative privileges, the most important feature of VirtualEnv is that it allows you to keep your environments separate. If you have one project that needs Foo version 2.3 and another that needs Foo version 1.5, you can't have them share the same environment; you have to keep their environments separate with VirtualEnv.

There are a few possibilities:

If you already know how to install Python modules, the default distutils setup already includes a per-user installation option. Just run python setup.py install --user instead of python setup.py install. This is the easiest, since this does not necessitate the addition of any source code.

You could also run the script with the directory of tweepy as the current working directory.

You could add an environment variable named PYTHONPATH to whatever environment (e.g., the shell) you use to run your script, and make it contain the path to tweepy.

If all else fails, and you really do want to edit your source code, you'll need to edit sys.path. sys.path is a list of locations where Python will look for code.

In your code, write:

import sys

sys.path.append("/path/to/your/tweepy/directory")

import tweepy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值