Traceback(most recent call last):File"Z:\Python\main.py", line 10,in<module>
module1.f()File"Z:\Python\module1.py", line 3,in f
print a
NameError:global name 'a'isnot defined
I’ve run into a bit of a wall importing modules in a Python script. I’ll do my best to describe the error, why I run into it, and why I’m tying this particular approach to solve my problem (which I will describe in a second):
Let’s suppose I have a module in which I’ve defined some utility functions/classes, which refer to entities defined in the namespace into which this auxiliary module will be imported (let “a” be such an entity):
module1:
def f():
print a
And then I have the main program, where “a” is defined, into which I want to import those utilities:
import module1
a=3
module1.f()
Executing the program will trigger the following error:
Traceback (most recent call last):
File "Z:\Python\main.py", line 10, in <module>
module1.f()
File "Z:\Python\module1.py", line 3, in f
print a
NameError: global name 'a' is not defined
Similar questions have been asked in the past (two days ago, d’uh) and several solutions have been suggested, however I don’t really think these fit my requirements. Here’s my particular context:
I’m trying to make a Python program which connects to a MySQL database server and displays/modifies data with a GUI. For cleanliness sake, I’ve defined the bunch of auxiliary/utility MySQL-related functions in a separate file. However they all have a common variable, which I had originally defined inside the utilities module, and which is the cursor object from MySQLdb module.
I later realised that the cursor object (which is used to communicate with the db server) should be defined in the main module, so that both the main module and anything that is imported into it can access that object.
End result would be something like this:
utilities_module.py:
def utility_1(args):
code which references a variable named "cur"
def utility_n(args):
etcetera
And my main module:
program.py:
import MySQLdb, Tkinter
db=MySQLdb.connect(#blahblah) ; cur=db.cursor() #cur is defined!
from utilities_module import *
And then, as soon as I try to call any of the utilities functions, it triggers the aforementioned “global name not defined” error.
A particular suggestion was to have a “from program import cur” statement in the utilities file, such as this:
utilities_module.py:
from program import cur
#rest of function definitions
program.py:
import Tkinter, MySQLdb
db=MySQLdb.connect(#blahblah) ; cur=db.cursor() #cur is defined!
from utilities_module import *
But that’s cyclic import or something like that and, bottom line, it crashes too. So my question is:
How in hell can I make the “cur” object, defined in the main module, visible to those auxiliary functions which are imported into it?
Thanks for your time and my deepest apologies if the solution has been posted elsewhere. I just can’t find the answer myself and I’ve got no more tricks in my book.
Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)
There are different ways to solve this, depending on your actual use case.
Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f as an instance method, rather than just a free function? Then you could do something like this:
Don’t use a from import unless the variable is intended to be a constant. from shared_stuff import a would create a new a variable initialized to whatever shared_stuff.a referred to at the time of the import, and this new a variable would not be affected by assignments to shared_stuff.a.
Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:
A function uses the globals of the module it’s defined in. Instead of setting a = 3, for example, you should be setting module1.a = 3. So, if you want cur available as a global in utilities_module, set utilities_module.cur.
A better solution: don’t use globals. Pass the variables you need into the functions that need it, or create a class to bundle all the data together, and pass it when initializing the instance.
This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don’t work for you if you made the same thing I did below.
Namely, I have a module which contains global/shared variables (as suggested above):
Then I had the main module which imports the shared stuff with:
import sharedstuff as shared
and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:
The easiest solution to this particular problem would have been to add another function within the module that would have stored the cursor in a variable global to the module. Then all the other functions could use it as well.
module1:
cursor = None
def setCursor(cur):
global cursor
cursor = cur
def method(some, args):
global cursor
do_stuff(cursor, some, args)
Since I haven’t seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict argument to the function requiring the calling module’s globals, and then pass the dict into the function when calling; e.g:
# external_module
def imported_function(global_dict=None):
print(global_dict["a"])
# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())
>>> 12
The OOP way of doing this would be to make your module a class instead of a set of unbound methods. Then you could use __init__ or a setter method to set the variables from the caller for use in the module methods.
import sys, time
from threading importThreaddef testexit():
time.sleep(5)
sys.exit()print"post thread exit"
t =Thread(target = testexit)
t.start()
t.join()print"pre main exit, post thread exit"
sys.exit()print"post main exit"
sys.exit()的文档指出,该调用应从Python退出。从该程序的输出中可以看到,“ post thread exit”从不打印,但即使在线程调用退出之后,主线程仍继续运行。
This could be a stupid question, but I’m testing out some of my assumptions about Python and I’m confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.
import sys, time
from threading import Thread
def testexit():
time.sleep(5)
sys.exit()
print "post thread exit"
t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"
The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that “post thread exit” is never printed, but the main thread just keeps on going even after the thread calls exit.
Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?
sys.exit() raises the SystemExit exception, as does thread.exit(). So, when sys.exit() raises that exception inside that thread, it has the same effect as calling thread.exit(), which is why only the thread exits.
What if I did want to exit the program
from the thread?
Apart from the method Deestan described you can call os._exit (notice the underscore). Before using it make sure that you understand that it does no cleanups (like calling __del__ or similar).
What if I did want to exit the program from the thread?
For Linux:
os.kill(os.getpid(), signal.SIGINT)
This sends a SIGINT to the main thread which raises a KeyboardInterrupt. With that you have a proper cleanup. Also you can register a handler, if you want to react differently.
The above does not work on Windows, as you can only send a SIGTERM signal, which is not handled by Python and has the same effect as sys._exit().
For Windows:
You can use:
sys._exit()
This will exit the entire process. However, without any cleanup. If you need that, you need to communicate with the main thread in another way.
Is the fact that “pre main exit, post thread exit” is printed what’s bothering you?
Unlike some other languages (like Java) where the analog to sys.exit (System.exit, in Java’s case) causes the VM/process/interpreter to immediately stop, Python’s sys.exit just throws an exception: a SystemExit exception in particular.
Here are the docs for sys.exit (just print sys.exit.__doc__):
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
This has a few consequences:
in a thread it just kills the current thread, not the entire process (assuming it gets all the way to the top of the stack…)
object destructors (__del__) are potentially invoked as the stack frames that reference those objects are unwound
finally blocks are executed as the stack unwinds
you can catch a SystemExit exception
The last is possibly the most surprising, and is yet another reason why you should almost never have an unqualified except statement in your Python code.
We’ve already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we’ve started adding:
from __future__ import unicode_literals
into our .py files (as we modify them). I’m wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).
# encoding: utf-8from __future__ import unicode_literalsimport two
name ='helló wörld from one'print name + two.name
运行的输出python one.py是:
Traceback(most recent call last):File"one.py", line 5,in<module>print name + two.nameUnicodeDecodeError:'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
在此示例中,two.name是utf-8编码的字符串(不是unicode),因为它没有导入unicode_literals,并且one.name是unicode字符串。当您将两者混合使用时,python会尝试解码编码后的字符串(假设它是ascii)并将其转换为unicode并失败。如果您这样做的话,它会起作用print name + two.name.decode('utf-8')。
如果您对字符串进行编码并稍后尝试将其混合,则可能会发生相同的情况。例如,这有效:
# encoding: utf-8
html ='<html><body>helló wörld</body></html>'if isinstance(html, unicode):
html = html.encode('utf-8')print'DEBUG: %s'% html
输出:
DEBUG:<html><body>helló wörld</body></html>
但是添加后,import unicode_literals它不会:
# encoding: utf-8from __future__ import unicode_literals
html ='<html><body>helló wörld</body></html>'if isinstance(html, unicode):
html = html.encode('utf-8')print'DEBUG: %s'% html
输出:
Traceback(most recent call last):File"test.py", line 6,in<module>print'DEBUG: %s'% htmlUnicodeDecodeError:'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)
The main source of problems I’ve had working with unicode strings is when you mix utf-8 encoded strings with unicode ones.
For example, consider the following scripts.
two.py
# encoding: utf-8
name = 'helló wörld from two'
one.py
# encoding: utf-8
from __future__ import unicode_literals
import two
name = 'helló wörld from one'
print name + two.name
The output of running python one.py is:
Traceback (most recent call last):
File "one.py", line 5, in <module>
print name + two.name
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
In this example, two.name is an utf-8 encoded string (not unicode) since it did not import unicode_literals, and one.name is an unicode string. When you mix both, python tries to decode the encoded string (assuming it’s ascii) and convert it to unicode and fails. It would work if you did print name + two.name.decode('utf-8').
The same thing can happen if you encode a string and try to mix them later.
For example, this works:
# encoding: utf-8
html = '<html><body>helló wörld</body></html>'
if isinstance(html, unicode):
html = html.encode('utf-8')
print 'DEBUG: %s' % html
Output:
DEBUG: <html><body>helló wörld</body></html>
But after adding the import unicode_literals it does NOT:
# encoding: utf-8
from __future__ import unicode_literals
html = '<html><body>helló wörld</body></html>'
if isinstance(html, unicode):
html = html.encode('utf-8')
print 'DEBUG: %s' % html
Output:
Traceback (most recent call last):
File "test.py", line 6, in <module>
print 'DEBUG: %s' % html
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 16: ordinal not in range(128)
It fails because 'DEBUG: %s' is an unicode string and therefore python tries to decode html. A couple of ways to fix the print are either doing print str('DEBUG: %s') % html or print 'DEBUG: %s' % html.decode('utf-8').
I hope this helps you understand the potential gotchas when using unicode strings.
I did find that if you add the unicode_literals directive you should also add something like:
# -*- coding: utf-8
to the first or second line your .py file. Otherwise lines such as:
foo = "barré"
result in an an error such as:
SyntaxError: Non-ASCII character '\xc3' in file mumble.py on line 198,
but no encoding declared; see http://www.python.org/peps/pep-0263.html
for details
Also take into account that unicode_literal will affect eval() but not repr() (an asymmetric behavior which imho is a bug), i.e. eval(repr(b'\xa4')) won’t be equal to b'\xa4' (as it would with Python 3).
Ideally, the following code would be an invariant, which should always work, for all combinations of unicode_literals and Python {2.7, 3.x} usage:
from __future__ import unicode_literals
bstr = b'\xa4'
assert eval(repr(bstr)) == bstr # fails in Python 2.7, holds in 3.1+
ustr = '\xa4'
assert eval(repr(ustr)) == ustr # holds in Python 2.7 and 3.1+
The second assertion happens to work, since repr('\xa4') evaluates to u'\xa4' in Python 2.7.
回答 4
还有更多。
有一些库和内建函数期望不容许unicode的字符串。
两个例子:
内置:
myenum = type('Enum',(), enum)
(略带色情)不适用于unicode_literals:type()需要字符串。
图书馆:
from wx.lib.pubsub import pub
pub.sendMessage("LOG MESSAGE", msg="no go for unicode literals")
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I’ve been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can’t get it to work properly and keep finding only how to do this when a date is involved.
Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I’m storing them in a list. I now need to calculate the average. I’m using regular expressions to parse out the original times and then doing the differences.
For the averaging, should I convert to seconds and then average?
Yes, definitely datetime is what you need here. Specifically, the strptime function, which parses a string into a time object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds, microseconds=tdelta.microseconds)
(of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case.
回答 1
尝试一下-在安排短期事件时非常有效。如果花费了一个多小时,那么最终的显示可能会需要一些友好的格式。
import time
start = time.time()
time.sleep(10)# or do something more productive
done = time.time()
elapsed = done - start
print(elapsed)
Try this — it’s efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting.
import time
start = time.time()
time.sleep(10) # or do something more productive
done = time.time()
elapsed = done - start
print(elapsed)
The time difference is returned as the number of elapsed seconds.
#!/usr/bin/env pythonfrom datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):if isinstance(start, datetime_time):# convert to datetimeassert isinstance(end, datetime_time)
start, end =[datetime.combine(datetime.min, t)for t in[start, end]]if start <= end:# e.g., 10:33:26-11:15:49return end - start
else:# end < start e.g., 23:55:00-00:25:00
end += timedelta(1)# +dayassert end > start
return end - start
for time_range in['10:33:26-11:15:49','23:55:00-00:25:00']:
s, e =[datetime.strptime(t,'%H:%M:%S')for t in time_range.split('-')]print(time_diff(s, e))assert time_diff(s, e)== time_diff(s.time(), e.time())
Here’s a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00 (a half an hour duration):
#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start
for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
Output
0:42:23
0:30:00
time_diff() returns a timedelta object that you can pass (as a part of the sequence) to a mean() function directly e.g.:
The mean() result is also timedelta() object that you can convert to seconds (td.total_seconds() method (since Python 2.7)), hours (td / timedelta(hours=1) (Python 3)), etc.
Structure that represent time difference in Python is called timedelta. If you have start_time and end_time as datetime types you can calculate the difference using - operator like:
diff = end_time - start_time
you should do this before converting to particualr string format (eg. before start_time.strftime(…)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.
Normally if you are just dealing with the time part you’d supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime for each with the day set to today and subtract the start from the stop time to get the interval (timedelta).
Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.
回答 10
如果您只是对24小时以下的时间感兴趣,请简明扼要。您可以根据需要在return语句中格式化输出:
import datetime
def elapsed_interval(start,end):
elapsed = end - start
min,secs=divmod(elapsed.days *86400+ elapsed.seconds,60)
hour, minutes = divmod(min,60)return'%.2d:%.2d:%.2d'%(hour,minutes,secs)if __name__ =='__main__':
time_start=datetime.datetime.now()""" do your process """
time_end=datetime.datetime.now()
total_time=elapsed_interval(time_start,time_end)
I have a string. How do I remove all text after a certain character? (In this case ...)
The text after will ... change so I that’s why I want to remove all characters after a certain one.
Split on your separator at most once, and take the first piece:
sep = '...'
stripped = text.split(sep, 1)[0]
You didn’t say what should happen if the separator isn’t present. Both this and Alex’s solution will return the entire string in that case.
回答 1
假设分隔符为“ …”,但它可以是任何字符串。
text ='some string... this part will be removed.'
head, sep, tail = text.partition('...')>>>print head
some string
如果找不到分隔符,head将包含所有原始字符串。
分区功能是在Python 2.5中添加的。
分区(…)S.partition(sep)->(head,sep,tail)
Searchesfor the separator sep in S,and returns the part before it,
the separator itself,and the part after it.If the separator isnot
found, returns S and two empty strings.
Searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it. If the separator is not
found, returns S and two empty strings.
For example, if string_to_split is a path like root/location/child/too_far.exe and you only want the folder path, you can split by "/".join(string_to_split.split("/")[:-1]) and you’ll get
root/location/child
import re
sep = '...'
with open("requirements.txt") as file_in:
lines = []
for line in file_in:
res = line.split(sep, 1)[0]
print(res)
回答 7
使用re的另一种简单方法是
import re, clr
text ='some string... this part will be removed.'
text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1)// text = some string
import re, clr
text = 'some string... this part will be removed.'
text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1)
// text = some string
Update: There is another reason to use the as syntax. Using , makes things a lot more ambiguous, as others have pointed out; and here’s what makes the difference. As of Python 2.6, there is multicatch which allows you to catch multiple exceptions in one except block. In such a situation, it’s more expressive and pythonic to say
the “as” syntax is the preferred one going forward, however if your code needs to work with older Python versions (2.6 is the first to support the new one) then you’ll need to use the comma syntax.
回答 3
如果要支持所有python版本,可以使用如下sys.exc_info()函数:
try:
a =1/'0'except(ZeroDivisionError,TypeError):
e = sys.exc_info()[1]print(e.args[0])
You can easily raise an exception in a lambda, if that’s what you really want to do.
def Raise(exception):
raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))
Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don’t think this is inherently evil, though–I consider the “y if x else z” syntax itself worse–just make sure you’re not trying to stuff too much into a lambda body.
Lambdas in Python are fairly restrictive with regard to what you’re allowed to use. Specifically, you can’t have any keywords (except for operators like and, not, or, etc) in their body.
So, there’s no way you could use a lambda for your example (because you can’t use raise), but if you’re willing to concede on that… You could use:
/usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py:734:InsecureRequestWarning:Unverified HTTPS request is being made.Adding certificate verification is strongly advised.See: https://urllib3.readthedocs.org/en/latest/security.html
InsecureRequestWarning)
The reason doing urllib3.disable_warnings() didn’t work for you is because it looks like you’re using a separate instance of urllib3 vendored inside of requests.
I gather this based on the path here: /usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py
To disable warnings in requests’ vendored urllib3, you’ll need to import that specific instance of the module:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
Per this github comment, one can disable urllib3 request warnings via requests in a 1-liner:
requests.packages.urllib3.disable_warnings()
This will suppress all warnings though, not just InsecureRequest (ie it will also suppress InsecurePlatform etc). In cases where we just want stuff to work, I find the conciseness handy.
requests ships with its own certificate bundle (but it can only be updated together with the module)
it will use (since requestsv2.4.0) the certifi package instead if it’s installed
The HTTPS certificate verification security measure isn’t something to be discarded light-heartedly. The Man-in-the-middle attack that it prevents safeguards you from a third party e.g. sipping a virus in or tampering with or stealing your data.
Why not using pyvmomi original functionSmartConnectNoSSL.
They added this function on June 14, 2016 and named it ConnectNoSSL, one day after they changed the name to SmartConnectNoSSL, use that instead of by passing the warning with unnecessary lines of code in your project?
Provides a standard method for connecting to a specified server without SSL
verification. Useful when connecting to servers with self-signed certificates
or when you wish to ignore SSL altogether
I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error “bash: pip: command not found”.
This is on Mac OS X, which I’m new too, so I’m assuming there’s some kind of path setting that was not set correctly when I ran setup.py. How can I investigate further? What do I need to check to get a better idea of the exact cause of the problem?
EDIT: I also tried installing Python 2.7 for Mac in the hopes that the friendly install process would do any housekeeping like editing PATH and whatever else needs to happy for everything to work according to the tutorials, but this didn’t work. After installing is running ‘python’ still ran Python 2.6 and PATH was not updated.
Why not just do sudo easy_install pip or if this is for python 2.6 sudo easy_install-2.6 pip?
This installs pip using the default python package installer system and saves you the hassle of manual set-up all at the same time.
This will allow you to then run the pip command for python package installation as it will be installed with the system python. I also recommend once you have pip using the virtualenv package and pattern. :)
回答 1
使用setuptools安装pip:
sudo easy_install pip
(我知道答案的上面部分对于klobucar来说是多余的,但是我还不能添加评论),所以这是一个解决方案 sudo: easy_install: command not found关于Debian / Ubuntu:
(I know the above part of my answer is redundant with klobucar’s, but I can’t add comments yet), so here’s an answer with a solution to sudo: easy_install: command not found on Debian/Ubuntu:
sudo apt-get install python-setuptools
Also, for python3, use easy_install3 and python3-setuptools.
pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)
pip3 should be installed automatically together with Python3.x. The documentation hasn’t been updated, so simply replace pip by pip3 in the instructions, when installing Flask for example.
Now, if this doesn’t work, you might have to install pip separately.
Update: A more reliable modern way to access the right pip install for the right python install is to use the syntax python -m pip.
Original Answer
pip would install itself into the bin of your python installation location. It also should create a symlink to some more common location like /usr/local/bin/pip
You can either edit your ~/.profile and update your PATH to include /Library/Frameworks/Python.framework/Versions/2.6/bin, or you could create a symlink to it in a place that you know is in your path.
If you do: echo $PATH, you should see the paths currently being searched. If /usr/local/bin is in your PATH, you can do:
Requirements for Installing Packages
This section describes the steps to follow before installing other Python packages.
Install pip, setuptools, and wheel If you have Python 2 >=2.7.9 or
Python 3 >=3.4 installed from python.org, you will already have pip
and setuptools, but will need to upgrade to the latest version:
On Linux or OS X:
pip install -U pip setuptools On Windows:
python -m pip install -U pip setuptools If you’re using a Python
install on Linux that’s managed by the system package manager (e.g
“yum”, “apt-get” etc…), and you want to use the system package manager
to install or upgrade pip, then see Installing pip/setuptools/wheel
with Linux Package Managers
I have to admit to being absolutely new to python, which I only need for one thing: awscli. I encountered this problem having downloaded python 3.x.x – pip: command not found
Whilst following the instructions for downloading the AWS cli I changed
pip install awscli
to
pip3 install awscli
which ran the correct version.
I’ve made an alias on my machine to run python3 whilst typing python, which would normally run the system version 2.7. I’m not sure this is a good idea now. I think I’ll just type in the commands as they intended them to be
insert the Homebrew directory at the top of your PATH environment variable. You can do this by adding the following line at the bottom of your ~/.profile file
(Context: My OS is Amazon linux using AWS. It seems similar to RedHat but it’s stripped down a bit, it seems.)
Exit the shell, then open a new shell. The pip command now works.
That’s what solved the problem at this location.
You might want to know as well: The pip commands to install software then needed to be written like this example (jupyter for example) to work correctly on my system:
pip install jupyter –user
Specifically, note the lack of sudo, and the presence of –user
Would be real nice if pip docs had said anything about all this, but that would take typing in more characters I guess.
Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:
sudo apt-get install python3-pip
(or sudo apt-get install python-pip for python 2)
回答 20
通过升级python 3解决了这个问题 brew upgrade python:现在我可以这样做:
pip3 install <package>==> python
Python has been installed as/usr/local/bin/python3
Unversioned symlinks `python`,`python-config`,`pip` etc. pointing to
`python3`,`python3-config`,`pip3` etc., respectively, have
Solved this by upgrading python 3 brew upgrade python:
Now i can just do:
pip3 install <package>
==> python
Python has been installed as
/usr/local/bin/python3
Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have
The problem seems that your python version and the library yoıu want to install is not matching versionally. Ex: If Django is Django3 and your python version is 2.7, you may get this error.
“After installing is running ‘python’ still ran Python 2.6 and PATH was not updated.”
1- Install latest version of Python
2- Change your PATH manually as python38 and compare them.
3- Try to reinstall.
I solved this problem as replacing PATH manually with the latest version of Python.
As for Windows: ;C:\python38\Scripts
This will surely install pip with all its dependencies. PS this is for python 3 if you want for python 2 replace python3 from the second command to python
To overcome the issue “bash: pip: command not found” in Mac
Found two versions on Mac 1 is 2.7 and the other is 3.7
when I say sudo easy_install pip, pip got installed under 2.7
when I say sudo easy_install-3.7 pip, pip got installed under 3.7
But, whenever I would require to do pip install , I wanted to install the package under python3.7, so I have set an alias (alias pip=pip3)in .bash_profile
so now, whenever I do pip install , it gets installed under python3.7