标签归档:python-2.6

导入模块中全局变量的可见性

问题:导入模块中全局变量的可见性

我在使用Python脚本导入模块时遇到了一些麻烦。我将尽力描述错误,为什么会遇到错误以及为什么要使用这种特殊方法来解决我的问题(我将在稍后描述):

假设我有一个模块,其中定义了一些实用程序函数/类,这些函数/类引用在此辅助模块将导入到的命名空间中定义的实体(让“ a”是这样的实体):

模块1:

def f():
    print a

然后,我有了主程序,其中定义了“ a”,我要将这些实用程序导入其中:

import module1
a=3
module1.f()

执行该程序将触发以下错误:

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

过去(两天前,d’uh)曾提出类似的问题,并提出了几种解决方案,但是我真的不认为这些符合我的要求。这是我的特定情况:

我正在尝试制作一个Python程序,该程序连接到MySQL数据库服务器并使用GUI显示/修改数据。为了简洁起见,我在一个单独的文件中定义了一堆与MySQL相关的辅助/实用程序功能。但是它们都有一个公共变量,该变量是我最初实用程序模块中定义的,并且是MySQLdb模块中的游标对象。后来我意识到,游标对象(用于与db服务器通信的对象)应该在主模块中定义,以便主模块和导入到其中的所有对象都可以访问该对象。

最终结果将是这样的:

utilities_module.py:

def utility_1(args):
    code which references a variable named "cur"
def utility_n(args):
    etcetera

而我的主要模块:

program.py:

import MySQLdb, Tkinter
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

然后,一旦我尝试调用任何实用程序函数,就会触发上述“未定义全局名称”错误。

一个特别的建议是在实用程序文件中有一个“ from program import cur”语句,例如:

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 *

但这是循环导入或类似的操作,最重要的是,它也崩溃了。所以我的问题是:

我该如何在主模块中定义的“ cur”对象对导入到其中的辅助功能可见?

如果您将解决方案发布在其他位置,则感谢您的宝贵时间和最深切的歉意。我只是自己找不到答案,而且我的书中没有其他花招。

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.


回答 0

Python中的全局变量是模块的全局变量,而不是所有模块的全局变量。(许多人对此感到困惑,因为在C语言中,除非您明确创建全局变量,否则所有实现文件中的全局变量都是相同的static。)

有多种解决方法,具体取决于您的实际用例。


在走这条路之前,请问自己这是否真的需要是全球性的。也许您真的想要一个带有f实例方法的类,而不仅仅是一个自由函数?然后,您可以执行以下操作:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

如果您确实确实想要一个全局变量,但是它只是供您使用module1,请在该模块中进行设置。

import module1
module1.a=3
module1.f()

另一方面,如果a由许多模块共享,则将其放置在其他位置,并让每个人都将其导入:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

…并且,在module1.py中:

import shared_stuff
def f():
    print shared_stuff.a

from除非变量打算是一个常量,否则不要使用导入。from shared_stuff import a会创建一个新a变量,初始化为shared_stuff.a导入时所引用的变量,并且该新a变量将不受分配的影响shared_stuff.a


或者,在极少数情况下,您确实确实需要它在任何地方都具有真正的全局性(例如内置),将其添加到内置模块中。确切的细节在Python 2.x和3.x之间有所不同。在3.x中,它的工作方式如下:

import builtins
import module1
builtins.a = 3
module1.f()

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:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

If you really do want a global, but it’s just there to be used by module1, set it in that module.

import module1
module1.a=3
module1.f()

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

… and, in module1.py:

import shared_stuff
def f():
    print shared_stuff.a

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:

import builtins
import module1
builtins.a = 3
module1.f()

回答 1

解决方法是,您可以考虑像这样在外层设置环境变量。

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

作为额外的预防措施,请在模块内部未定义MYVAL的情况下进行处理。

As a workaround, you could consider setting environment variables in the outer layer, like this.

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

As an extra precaution, handle the case when MYVAL is not defined inside the module.


回答 2

函数使用其定义模块的全局变量。a = 3例如,应该设置而不是set module1.a = 3。因此,如果要cur用作全局输入utilities_module,请设置utilities_module.cur

更好的解决方案:不要使用全局变量。将所需的变量传递到需要它的函数中,或者创建一个类将所有数据捆绑在一起,并在初始化实例时传递它。

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.


回答 3

这篇文章只是我遇到的Python行为的观察。如果您做的事情与我在下面做的相同,则上面阅读的建议可能对您不起作用。

即,我有一个包含全局/共享变量的模块(如上所述):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

然后,我有一个主要模块,用于导入共享内容:

import sharedstuff as shared

以及实际填充这些数组的其他一些模块。这些由主模块调用。当退出这些其他模块时,我可以清楚地看到已填充了阵列。但是,当在主模块中重新读取它们时,它们为空。这对我来说很奇怪(嗯,我是Python的新手)。但是,当我将主模块中的sharedstuff.py导入方式更改为:

from globals import *

它有效(填充了数组)。

只是在说’

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):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

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:

from globals import *

it worked (the arrays were populated).

Just sayin’


回答 4

解决此特定问题的最简单方法是在模块内添加另一个功能,该功能会将光标存储在模块的全局变量中。然后所有其他功能也可以使用它。

模块1:

cursor = None

def setCursor(cur):
    global cursor
    cursor = cur

def method(some, args):
    global cursor
    do_stuff(cursor, some, args)

主程序:

import module1

cursor = get_a_cursor()
module1.setCursor(cursor)
module1.method()

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)

main program:

import module1

cursor = get_a_cursor()
module1.setCursor(cursor)
module1.method()

回答 5

由于全局变量是特定于模块的,因此可以将以下函数添加到所有导入的模块中,然后将其用于:

  • 将单数变量(以字典格式)添加为这些变量的全局变量
  • 将您的模块全局变量传递给它。

addglobals = lambda x:globals()。update(x)

然后,您需要传递当前的全局变量是:

导入模块

module.addglobals(globals())

Since globals are module specific, you can add the following function to all imported modules, and then use it to:

  • Add singular variables (in dictionary format) as globals for those
  • Transfer your main module globals to it .

addglobals = lambda x: globals().update(x)

Then all you need to pass on current globals is:

import module

module.addglobals(globals())


回答 6

由于我在上面的答案中没有看到它,因此我想我将添加一个简单的解决方法,global_dict即向需要调用模块全局变量的函数添加一个参数,然后在调用时将dict传递给该函数。例如:

# 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

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

回答 7

这样做的OOP方法是使模块成为类,而不是一组未绑定的方法。然后,您可以使用__init__或setter方法来设置来自调用方的变量,以用于模块方法中。

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.


为什么在Python的线程内调用sys.exit()时不退出?

问题:为什么在Python的线程内调用sys.exit()时不退出?

这可能是一个愚蠢的问题,但是我正在测试我对Python的一些假设,并对为什么以下代码段在线程中调用时不退出而在主线程中调用时退出而感到困惑。

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"

sys.exit()的文档指出,该调用应从Python退出。从该程序的输出中可以看到,“ post thread exit”从不打印,但即使在线程调用退出之后,主线程仍继续运行。

是否为每个线程创建了一个单独的解释器实例,并且对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)?


回答 0

sys.exit()和一样引发SystemExit异常thread.exit()。因此,当sys.exit()在该线程内引发该异常时,它的作用与调用相同thread.exit(),这就是为什么只有该线程退出的原因。

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.


回答 1

如果我确实想从线程中退出程序怎么办?

除了Deestan描述的方法之外,您还可以调用os._exit(注意下划线)。使用之前,请确保你明白,它没有清理(如呼叫__del__或类似)。

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).


回答 2

如果我确实想从线程中退出程序怎么办(不是我真正想要的,但据我所知)?

至少在Linux上,您可以执行以下操作:

os.kill(os.getpid(), signal.SIGINT)

这会将a发送SIGINT到主线程,并引发a KeyboardInterrupt。这样您就可以进行适当的清理了。如果需要,您甚至可以处理信号。

顺便说一句:在Windows上,您只能发送SIGTERM信号,而Python无法捕获该信号。在这种情况下,您可以简单地使用os._exit相同的效果。

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.


回答 3

是“打印前主出口,线程后出口”的事实困扰着您吗?

与其他语言(如Java)不同,其他语言(如Java)的类似物sys.exitSystem.exit在Java中为Java)会导致VM /进程/解释器立即停止,而Python sys.exit只是抛出一个异常:特别是SystemExit异常。

以下是sys.exit(just print sys.exit.__doc__)的文档:

通过提高SystemExit(status)退出解释器。
如果省略状态或无,则默认为零(即成功)。
如果状态为数字,则将其用作系统退出状态。
如果是另一种对象,则将其打印出来,并且系统
退出状态将为1(即失败)。

这会带来一些后果:

  • 在一个线程中,它只是杀死当前线程,而不是杀死整个进程(假设它一直到达栈顶…)
  • __del__当引用那些对象的堆栈框架被展开时,可能会调用对象析构函数()
  • 最后,在堆栈展开时执行块
  • 你可以抓住一个SystemExitexceptions

最后一个可能是最令人惊讶的,也是另一个原因,为什么您几乎不应except在Python代码中使用不合格的语句。

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.


回答 4

如果我确实想从线程中退出程序怎么办(不是我真正想要的,但据我所知)?

我的首选方法是传递Erlang-ish消息。稍微简化一下,我这样做是这样的:

import sys, time
import threading
import Queue # thread-safe

class CleanExit:
  pass

ipq = Queue.Queue()

def testexit(ipq):
  time.sleep(5)
  ipq.put(CleanExit)
  return

threading.Thread(target=testexit, args=(ipq,)).start()
while True:
  print "Working..."
  time.sleep(1)
  try:
    if ipq.get_nowait() == CleanExit:
      sys.exit()
  except Queue.Empty:
    pass

What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?

My preferred method is Erlang-ish message passing. Slightly simlified, I do it like this:

import sys, time
import threading
import Queue # thread-safe

class CleanExit:
  pass

ipq = Queue.Queue()

def testexit(ipq):
  time.sleep(5)
  ipq.put(CleanExit)
  return

threading.Thread(target=testexit, args=(ipq,)).start()
while True:
  print "Working..."
  time.sleep(1)
  try:
    if ipq.get_nowait() == CleanExit:
      sys.exit()
  except Queue.Empty:
    pass

在Python 2.6中使用unicode_literals有任何陷阱吗?

问题:在Python 2.6中使用unicode_literals有任何陷阱吗?

我们已经获得了在Python 2.6下运行的代码库。为了准备Python 3.0,我们开始添加:

从__future__导入unicode_literals

进入我们的.py文件(我们对其进行修改)。我想知道是否还有其他人正在这样做并且遇到了任何非显而易见的陷阱(也许在花费大量时间进行调试之后)。

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).


回答 0

我处理unicode字符串的主要问题来源是将utf-8编码的字符串与unicode的字符串混合使用。

例如,考虑以下脚本。

py

# encoding: utf-8
name = 'helló wörld from two'

一个

# encoding: utf-8
from __future__ import unicode_literals
import 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.name
UnicodeDecodeError: '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-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

输出:

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)

它失败,因为它'DEBUG: %s'是一个unicode字符串,因此python尝试解码html。修复打印件的几种方法正在执行print str('DEBUG: %s') % htmlprint 'DEBUG: %s' % html.decode('utf-8')

我希望这可以帮助您了解使用unicode字符串时的潜在陷阱。

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.


回答 1

同样在2.6中(在python 2.6.5 RC1 +之前),unicode文字不能与关键字参数配合使用(issue4978):

例如,以下代码在不使用unicode_literals的情况下有效,但由于TypeError而失败:keywords must be string如果使用unicode_literals。

  >>> def foo(a=None): pass
  ...
  >>> foo(**{'a':1})
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
      TypeError: foo() keywords must be strings

Also in 2.6 (before python 2.6.5 RC1+) unicode literals doesn’t play nice with keyword arguments (issue4978):

The following code for example works without unicode_literals, but fails with TypeError: keywords must be string if unicode_literals is used.

  >>> def foo(a=None): pass
  ...
  >>> foo(**{'a':1})
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
      TypeError: foo() keywords must be strings

回答 2

我确实发现,如果添加unicode_literals指令,则还应该添加如下内容:

 # -*- coding: utf-8

.py文件的第一行或第二行。否则,例如:

 foo = "barré"

导致错误,例如:

语法错误:第198行的文件mumble.py中的非ASCII字符'\ xc3',
 但未声明编码;参见http://www.python.org/peps/pep-0263.html
 详情

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

回答 3

还应考虑到unicode_literal将影响eval()但不会repr()(不对称的行为,恕我直言是一个错误),即eval(repr(b'\xa4'))不等于b'\xa4'(与Python 3一样)。

理想情况下,以下代码对于unicode_literals和Python {2.7,3.x}用法的所有组合都是不变的,应该始终有效:

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+

第二个断言恰好起作用,因为repr('\xa4')u'\xa4'在Python 2.7中得到评估。

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")

不起作用:wx pubsub库需要字符串消息类型。

前者很深奥,很容易固定

myenum = type(b'Enum', (), enum)

但是如果您的代码中充满了对pub.sendMessage()的调用(后者是我的),那么后者将是毁灭性的。

ang,是吗?!?

There are more.

There are libraries and builtins that expect strings that don’t tolerate unicode.

Two examples:

builtin:

myenum = type('Enum', (), enum)

(slightly esotic) doesn’t work with unicode_literals: type() expects a string.

library:

from wx.lib.pubsub import pub
pub.sendMessage("LOG MESSAGE", msg="no go for unicode literals")

doesn’t work: the wx pubsub library expects a string message type.

The former is esoteric and easily fixed with

myenum = type(b'Enum', (), enum)

but the latter is devastating if your code is full of calls to pub.sendMessage() (which mine is).

Dang it, eh?!?


回答 5

如果from __future__ import unicode_literals在您使用的位置导入了任何模块,则Click将在所有位置引发unicode异常click.echo。一场噩梦…

Click will raise unicode exceptions all over the place if any module that has from __future__ import unicode_literals is imported where you use click.echo. It’s a nightmare…


如何计算两个时间字符串之间的时间间隔

问题:如何计算两个时间字符串之间的时间间隔

我有两次,开始时间和停止时间,格式为10:33:26(HH:MM:SS)。我需要两次之间的区别。我一直在浏览Python文档并在线搜索,我想这可能与datetime和/或time模块有关。我无法使其正常工作,并且仅在涉及约会时才继续寻找如何执行此操作。

最终,我需要计算多个持续时间的平均值。我得到了可以工作的时差,并将它们存储在列表中。我现在需要计算平均值。我正在使用正则表达式解析原始时间,然后进行区别。

对于平均,我应该转换为秒然后平均吗?

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?


回答 0

是的,datetime这里绝对是您所需要的。具体来说,是strptime将字符串解析为时间对象的函数。

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)

这样就得到了一个timedelta包含两次差异的对象。您可以执行此操作,例如将其转换为秒或将其添加到另一个datetime

如果结束时间早于开始时间,则返回否定结果,例如s1 = 12:00:00s2 = 05:00:00。如果在这种情况下,如果您希望代码假定间隔经过午夜(即应该假定结束时间永远不会早于开始时间),则可以在上面的代码中添加以下几行:

if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)

(当然,您需要在from datetime import timedelta某处添加)。感谢JF Sebastian指出了这个用例。

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.


回答 2

即使结束时间小于开始时间(超过午夜间隔),例如23:55:00-00:25:00(半小时),这也是一种支持找到差异的解决方案:

#!/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())

输出量

0:42:23
0:30:00

time_diff()返回一个timedelta对象,您可以将其直接(作为序列的一部分)传递给mean()函数,例如:

#!/usr/bin/env python
from datetime import timedelta

def mean(data, start=timedelta(0)):
    """Find arithmetic average."""
    return sum(data, start) / len(data)

data = [timedelta(minutes=42, seconds=23), # 0:42:23
        timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds

mean()结果也是timedelta()对象,可转换为秒(td.total_seconds()方法(因为Python 2.7)),小时(td / timedelta(hours=1)(Python 3中)),等等。

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.:

#!/usr/bin/env python
from datetime import timedelta

def mean(data, start=timedelta(0)):
    """Find arithmetic average."""
    return sum(data, start) / len(data)

data = [timedelta(minutes=42, seconds=23), # 0:42:23
        timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds

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.


回答 3

表示Python中时差的结构称为timedelta。如果有start_timeend_time作为datetime类型,则可以使用以下-运算符来计算差异:

diff = end_time - start_time

您应该在转换为特定的字符串格式之前执行此操作(例如,在start_time.strftime(…)之前)。如果您已经有了字符串表示形式,则需要使用strptime方法将其转换回时间/日期时间。

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.


回答 4

网站说尝试:

import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt) 
diff.seconds/60 

本论坛使用time.mktime()

This site says to try:

import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt) 
diff.seconds/60 

This forum uses time.mktime()


回答 5

我喜欢这个人的做法-https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps。不知道它是否有缺点。

但是对我来说看起来很整洁:)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

关于这个问题,您仍然需要datetime.strptime()像其他人所说的那样使用。

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

Regarding to the question you still need to use datetime.strptime() as others said earlier.


回答 6

试试这个

import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time

输出:

0:00:05

Try this

import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time

OUTPUT :

0:00:05

回答 7

import datetime as dt
from dateutil.relativedelta import relativedelta

start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
    timedelta_obj.years,
    timedelta_obj.months,
    timedelta_obj.days,
    timedelta_obj.hours,
    timedelta_obj.minutes,
    timedelta_obj.seconds,
)

结果:0 0 0 0 -47 -37

import datetime as dt
from dateutil.relativedelta import relativedelta

start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
    timedelta_obj.years,
    timedelta_obj.months,
    timedelta_obj.days,
    timedelta_obj.hours,
    timedelta_obj.minutes,
    timedelta_obj.seconds,
)

result: 0 0 0 0 -47 -37


回答 8

两者timedatetime都有日期部分。

通常,如果您只处理时间部分,则需要提供默认日期。如果您只是对两者之间的差异感兴趣,并且知道两个时间都在同一天,datetime则为每个日期构造一个a ,并将日期设置为今天,然后从停止时间中减去开始时间以获取时间间隔(timedelta)。

Both time and datetime have a date component.

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).


回答 9

看一下datetime模块和timedelta对象。您应该最终为开始时间和结束时间构造一个datetime对象,然后减去它们,您将获得一个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)

Concise if you are just interested in the time elapsed that is under 24 hours. You can format the output as needed in the return statement :

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)

如何在python中删除特定字符之后的所有字符?

问题:如何在python中删除特定字符之后的所有字符?

我有一个字符串。如何删除某个字符后的所有文本?(在这种情况下...)之后
的文本将...更改,所以这就是为什么我要删除某个字符之后的所有字符的原因。

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.


回答 0

最多在分隔器上分割一次,然后取下第一块:

sep = '...'
rest = text.split(sep, 1)[0]

您没有说如果不使用分隔符该怎么办。在这种情况下,此方法和Alex的解决方案都将返回整个字符串。

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)

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.

Assuming your separator is ‘…’, but it can be any string.

text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')

>>> print head
some string

If the separator is not found, head will contain all of the original string.

The partition function was added in Python 2.5.

partition(…) S.partition(sep) -> (head, sep, tail)

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.

回答 2

如果要删除字符串中最后一次出现分隔符之后的所有内容,我会发现这很有效:

<separator>.join(string_to_split.split(<separator>)[:-1])

例如,如果 string_to_split是像一个路径root/location/child/too_far.exe,你只需要在文件夹路径,您可以通过拆分"/".join(string_to_split.split("/")[:-1]),你会得到 root/location/child

If you want to remove everything after the last occurrence of separator in a string I find this works well:

<separator>.join(string_to_split.split(<separator>)[:-1])

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


回答 3

没有RE(我想是您想要的):

def remafterellipsis(text):
  where_ellipsis = text.find('...')
  if where_ellipsis == -1:
    return text
  return text[:where_ellipsis + 3]

或者,使用RE:

import re

def remwithre(text, there=re.compile(re.escape('...')+'.*')):
  return there.sub('', text)

Without a RE (which I assume is what you want):

def remafterellipsis(text):
  where_ellipsis = text.find('...')
  if where_ellipsis == -1:
    return text
  return text[:where_ellipsis + 3]

or, with a RE:

import re

def remwithre(text, there=re.compile(re.escape('...')+'.*')):
  return there.sub('', text)

回答 4

find方法将返回字符串中的字符位置。然后,如果要从角色中删除所有内容,请执行以下操作:

mystring = "123⋯567"
mystring[ 0 : mystring.index("⋯")]

>> '123'

如果要保留字符,请在字符位置加1。

The method find will return the character position in a string. Then, if you want remove every thing from the character, do this:

mystring = "123⋯567"
mystring[ 0 : mystring.index("⋯")]

>> '123'

If you want to keep the character, add 1 to the character position.


回答 5

import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)

输出:“这是一个测试”

import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)

Output: “This is a test”


回答 6

从文件中:

import re
sep = '...'

with open("requirements.txt") as file_in:
    lines = []
    for line in file_in:
        res = line.split(sep, 1)[0]
        print(res)

From a file:

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

another easy way using re will be

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

如何在python中将集合转换为列表?

问题:如何在python中将集合转换为列表?

我正在尝试将一组转换为Python 2.6中的列表。我正在使用以下语法:

first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

但是,我得到以下堆栈跟踪:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

我怎样才能解决这个问题?

I am trying to convert a set to a list in Python 2.6. I’m using this syntax:

first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

However, I get the following stack trace:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

How can I fix this?


回答 0

已经是清单了

type(my_set)
>>> <type 'list'>

你想要类似的东西吗

my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]

编辑:您的最后评论的输出

>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]

我想知道您是否做了这样的事情:

>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

It is already a list

type(my_set)
>>> <type 'list'>

Do you want something like

my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]

EDIT : Output of your last comment

>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]

I’m wondering if you did something like this :

>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

回答 1

代替:

first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

为什么不简化该过程:

my_list = list(set([1,2,3,4])

这将从您的列表中删除重复对象,并将列表返回给您。

Instead of:

first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

Why not shortcut the process:

my_list = list(set([1,2,3,4])

This will remove the dupes from you list and return a list back to you.


回答 2

[编辑]似乎您之前已经重新定义了“列表”,将其用作变量名,如下所示:

list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

你会得到

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

[EDITED] It’s seems you earlier have redefined “list”, using it as a variable name, like this:

list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

And you’l get

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

回答 3

每当遇到此类问题时,请尝试使用以下方法查找要首先转换的元素的数据类型:

type(my_set)

然后,使用:

  list(my_set) 

将其转换为列表。您现在可以像使用python中的任何普通列表一样使用新建列表。

Whenever you are stuck in such type of problems, try to find the datatype of the element you want to convert first by using :

type(my_set)

Then, Use:

  list(my_set) 

to convert it to a list. You can use the newly built list like any normal list in python now.


回答 4

只需键入:

list(my_set)

这会将格式为{‘1’,’2’}的集合转换为格式为[‘1’,’2’]的列表。

Simply type:

list(my_set)

This will turn a set in the form {‘1′,’2’} into a list in the form [‘1′,’2’].


回答 5

查看您的第一行。您的堆栈跟踪信息显然不是来自您在此处粘贴的代码,因此我不知道您到底做了什么。

>>> my_set=([1,2,3,4])
>>> my_set
[1, 2, 3, 4]
>>> type(my_set)
<type 'list'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>

你想要的是set([1, 2, 3, 4])

>>> my_set = set([1, 2, 3, 4])
>>> my_set
set([1, 2, 3, 4])
>>> type(my_set)
<type 'set'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>

“不可调用”异常表示您正在执行类似操作set()()-尝试调用set实例。

Review your first line. Your stack trace is clearly not from the code you’ve pasted here, so I don’t know precisely what you’ve done.

>>> my_set=([1,2,3,4])
>>> my_set
[1, 2, 3, 4]
>>> type(my_set)
<type 'list'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>

What you wanted was set([1, 2, 3, 4]).

>>> my_set = set([1, 2, 3, 4])
>>> my_set
set([1, 2, 3, 4])
>>> type(my_set)
<type 'set'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>

The “not callable” exception means you were doing something like set()() – attempting to call a set instance.


回答 6

我不确定您是否正在使用此([1, 2])语法创建一个集合,而不是一个列表。要创建集合,您应该使用set([1, 2])

这些括号只是包裹住您的表达方式,就像您会写的那样:

if (condition1
    and condition2 == 3):
    print something

并没有真正被忽略,但是对您的表情什么也不做。

注意:(something, something_else)将创建一个元组(但仍然没有列表)。

I’m not sure that you’re creating a set with this ([1, 2]) syntax, rather a list. To create a set, you should use set([1, 2]).

These brackets are just envelopping your expression, as if you would have written:

if (condition1
    and condition2 == 3):
    print something

There’re not really ignored, but do nothing to your expression.

Note: (something, something_else) will create a tuple (but still no list).


回答 7

Python是一种动态类型化的语言,这意味着您不能像在C或C ++中那样定义变量的类型:

type variable = value

要么

type variable(value)

在Python中,如果更改类型或类型的初始化函数(构造函数)来声明类型的变量,则可以使用强制转换:

my_set = set([1,2,3])
type my_set

会给你<type 'set'>答案。

如果有列表,请执行以下操作:

my_list = [1,2,3]
my_set = set(my_list)

Python is a dynamically typed language, which means that you cannot define the type of the variable as you do in C or C++:

type variable = value

or

type variable(value)

In Python, you use coercing if you change types, or the init functions (constructors) of the types to declare a variable of a type:

my_set = set([1,2,3])
type my_set

will give you <type 'set'> for an answer.

If you have a list, do this:

my_list = [1,2,3]
my_set = set(my_list)

回答 8

嗯,我敢打赌,在前面的几行中,您会看到以下内容:

list = set(something)

我错了吗 ?

Hmmm I bet that in some previous lines you have something like:

list = set(something)

Am I wrong ?


Python试试…除逗号与“ as”外

问题:Python试试…除逗号与“ as”外

在except语句中“,”和“ as”之间有什么区别,例如:

try:
    pass
except Exception, exception:
    pass

和:

try:
    pass
except Exception as exception:
    pass

2.6中的第二种语法合法吗?它可以在Windows上的CPython 2.6中运行,但是cygwin中的2.5解释器抱怨它无效。

如果它们在2.6中均有效,那我应该使用哪个?

What is the difference between ‘,’ and ‘as’ in except statements, eg:

try:
    pass
except Exception, exception:
    pass

and:

try:
    pass
except Exception as exception:
    pass

Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that it is invalid.

If they are both valid in 2.6 which should I use?


回答 0

权威性文件是PEP-3110:捕获异常

摘要:

  • 在Python 3.x中,使用as要求对异常分配给一个变量。
  • 在Python 2.6+中,请使用as语法,因为它的模棱两可远,并且与Python 3.x向前兼容。
  • as不支持Python 2.5和更早版本的情况下,请使用逗号版本。

The definitive document is PEP-3110: Catching Exceptions

Summary:

  • In Python 3.x, using as is required to assign an exception to a variable.
  • In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x.
  • In Python 2.5 and earlier, use the comma version, since as isn’t supported.

回答 1

是的,这是合法的。我正在运行python 2.6

try:
    [] + 3
except Exception as x:
    print "woo hoo"

>>> 
woo hoo

更新:使用该as语法还有另一个原因。,正如其他人指出的那样,使用会使事情变得更加模棱两可。这就是与众不同的原因。从Python 2.6开始,有multicatch一个功能允许您在一个代码except块中捕获多个异常。在这种情况下,说起来更具表现力和Python风格

except (exception1, exception2) as e

而不是说

except (exception1, exception2), e

仍然可以工作

Yes it’s legal. I’m running Python 2.6

try:
    [] + 3
except Exception as x:
    print "woo hoo"

>>> 
woo hoo

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

except (exception1, exception2) as e

rather than to say

except (exception1, exception2), e

which would still work


回答 2

“ as”语法是首选的语法,但是,如果您的代码需要使用较旧的Python版本(第一个支持新版本的2.6是),则需要使用逗号语法。

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])

(来源:http : //python3porting.com/noconv.html

If you want to support all python versions you can use the sys.exc_info() function like this:

try:
    a = 1/'0'
except (ZeroDivisionError, TypeError):
    e = sys.exc_info()[1]
    print(e.args[0])

(source:http://python3porting.com/noconv.html)


回答 4

从Python 3.7开始(不确定其他版本),不再支持’逗号’语法:

源文件exception_comma.py

try:
    result = 1/0
except Exception, e:
    print("An error occurred")
    exit(1)

exit(0)
  • $ python --version --> Python 2.7.10
$ python exception_comma.py
An error occurred
  • $ python3 --version --> Python 3.7.2
$ python3 exception_comma.py
  File "exception_comma.py", line 3
    except Exception, e:
                    ^
SyntaxError: invalid syntax

As of Python 3.7 (not sure about other versions) the ‘comma’ syntax is not supported any more:

Source file exception_comma.py:

try:
    result = 1/0
except Exception, e:
    print("An error occurred")
    exit(1)

exit(0)
  • $ python --version --> Python 2.7.10
$ python exception_comma.py
An error occurred
  • $ python3 --version --> Python 3.7.2
$ python3 exception_comma.py
  File "exception_comma.py", line 3
    except Exception, e:
                    ^
SyntaxError: invalid syntax

有没有办法在python的lambda中执行“如果”

问题:有没有办法在python的lambda中执行“如果”

python 2.6中,我想这样做:

f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception

这显然不是语法。是否可以执行ifin lambda,如果可以,该怎么做?

谢谢

In python 2.6, I want to do:

f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception

This clearly isn’t the syntax. Is it possible to perform an if in lambda and if so how to do it?

thanks


回答 0

您要寻找的语法:

lambda x: True if x % 2 == 0 else False

但是您不能使用printraise使用lambda。

The syntax you’re looking for:

lambda x: True if x % 2 == 0 else False

But you can’t use print or raise in a lambda.


回答 1

为什么不只是定义一个函数?

def f(x):
    if x == 2:
        print(x)
    else:
        raise ValueError

在这种情况下,确实没有理由使用lambda。

why don’t you just define a function?

def f(x):
    if x == 2:
        print(x)
    else:
        raise ValueError

there really is no justification to use lambda in this case.


回答 2

到目前为止,我可能写的最糟糕的python行:

f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])

如果您打印x == 2,

如果x!= 2,则加注。

Probably the worst python line I’ve written so far:

f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])

If x == 2 you print,

if x != 2 you raise.


回答 3

如果您确实要这样做,则可以在lambda中轻松引发异常。

def Raise(exception):
    raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))

这是一个好主意吗?我的本能通常是将错误报告放在lambda之外。使其值为None并在调用方中引发错误。不过,我不认为这从本质上讲是邪恶的-我认为“ y if x else z”语法本身更糟-只需确保您没有试图将过多内容放入lambda主体即可。

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.


回答 4

就允许使用的内容而言,Python中的Lambda相当严格。特别是,你不能有任何关键字(除了运营商喜欢andnotor,等)在他们的身上。

因此,您无法在示例中使用lambda(因为您无法使用raise),但是如果您愿意就此作答,则可以使用:

f = lambda x: x == 2 and x or None

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:

f = lambda x: x == 2 and x or None

回答 5

请注意,您可以在lambda定义中使用其他else … if语句:

f = lambda x: 1 if x>0 else 0 if x ==0 else -1

note you can use several else…if statements in your lambda definition:

f = lambda x: 1 if x>0 else 0 if x ==0 else -1

回答 6

如果仍要打印,则可以导入以后的模块

from __future__ import print_function

f = lambda x: print(x) if x%2 == 0 else False

If you still want to print you can import future module

from __future__ import print_function

f = lambda x: print(x) if x%2 == 0 else False

回答 7

您还可以使用逻辑运算符来进行类似条件运算的操作

func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse

您可以在此处查看有关逻辑运算符的更多信息

You can also use Logical Operators to have something like a Conditional

func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse

You can see more about Logical Operators here


回答 8

您真正需要的是

def fun():
    raise Exception()
f = lambda x:print x if x==2 else fun()

现在以您需要的方式调用该函数

f(2)
f(3)

what you need exactly is

def fun():
    raise Exception()
f = lambda x:print x if x==2 else fun()

now call the function the way you need

f(2)
f(3)

回答 9

此代码段应帮助您:

x = lambda age: 'Older' if age > 30 else 'Younger'

print(x(40))

This snippet should help you:

x = lambda age: 'Older' if age > 30 else 'Younger'

print(x(40))

回答 10

以下示例代码对我有用。不知道它是否与这个问题直接相关,但希望在其他情况下有帮助。

a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))

Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.

a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))

回答 11

尝试一下:

is_even = lambda x: True if x % 2 == 0 else False
print(is_even(10))
print(is_even(11))

出:

True
False

Try it:

is_even = lambda x: True if x % 2 == 0 else False
print(is_even(10))
print(is_even(11))

Out:

True
False

回答 12

在lambda中执行if的一种简单方法是使用列表理解。

您不能在lambda中引发异常,但这是Python 3.x中一种类似于您的示例的方式:

f = lambda x: print(x) if x==2 else print("exception")

另一个例子:

如果M则返回1,否则返回0

f = lambda x: 1 if x=="M" else 0

An easy way to perform an if in lambda is by using list comprehension.

You can’t raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:

f = lambda x: print(x) if x==2 else print("exception")

Another example:

return 1 if M otherwise 0

f = lambda x: 1 if x=="M" else 0

禁止InsecureRequestWarning:在Python2.6中发出未经验证的HTTPS请求

问题:禁止InsecureRequestWarning:在Python2.6中发出未经验证的HTTPS请求

我正在使用pyVmomi并使用一种连接方法在Python2.6中编写脚本:

service_instance = connect.SmartConnect(host=args.ip,
                                        user=args.user,
                                        pwd=args.password)

我收到以下警告:

/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)

有趣的是,我没有随pip一起安装urllib3(但在/usr/lib/python2.6/site-packages/requests/packages/urllib3/中)。

我已经尝试按照这里的建议

import urllib3
...
urllib3.disable_warnings()

但这并没有改变任何东西。

I am writing scripts in Python2.6 with use of pyVmomi and while using one of the connection methods:

service_instance = connect.SmartConnect(host=args.ip,
                                        user=args.user,
                                        pwd=args.password)

I get the following warning:

/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)

What’s interesting is that I do not have urllib3 installed with pip (but it’s there in /usr/lib/python2.6/site-packages/requests/packages/urllib3/).

I have tried as suggested here

import urllib3
...
urllib3.disable_warnings()

but that didn’t change anything.


回答 0

您可以通过PYTHONWARNINGS环境变量禁用任何Python警告。在这种情况下,您需要:

export PYTHONWARNINGS="ignore:Unverified HTTPS request"

要禁用使用Python代码(requests >= 2.16.0):

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

对于requests < 2.16.0,请参见下面的原始答案。

原始答案

这样urllib3.disable_warnings()做对您不起作用的原因是,您似乎正在使用请求中提供的urllib3的单独实例。

我根据这里的路径收集此信息: /usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py

要在请求的供应商urllib3中禁用警告,您需要导入模块的特定实例:

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

You can disable any Python warnings via the PYTHONWARNINGS environment variable. In this case, you want:

export PYTHONWARNINGS="ignore:Unverified HTTPS request"

To disable using Python code (requests >= 2.16.0):

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

For requests < 2.16.0, see original answer below.

Original answer

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)

回答 1

这是在2017年的答案urllib3不是的一部分requests

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

This is the answer in 2017. urllib3 not a part of requests anymore

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

回答 2

根据这个github评论,可以urllib3通过requests1-liner 禁用请求警告:

requests.packages.urllib3.disable_warnings()

但这不仅会抑制所有警告InsecureRequest(即也会抑制InsecurePlatform等)。如果我们只是想让东西起作用,我会觉得简洁很方便。

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.


回答 3

正确的方法是阅读所提供链接上的相关部分,并按照说明进行操作。根据CA证书-高级用法-要求2.8.1文档的特定方式requests(捆绑有其自己的副本urllib3):

  • requests 带有自己的证书捆绑包(但只能与模块一起更新)
  • 它将使用(因为requests v2.4.0certifi,而不是如果已安装它

HTTPS证书验证安全性措施不能轻易丢弃。它阻止了中间人攻击,从而保护了您免受第三方的侵害,例如在其中感染病毒,篡改或窃取数据。

如今,借助政府支持的全球黑客攻击活动(如量身定制的访问操作针对中国网络基础架构的中国防火墙),您比您想象的更有可能。

The correct way is to read the relevant section on the provided link and do as it says. The way specific for requests (which bundles with its own copy of urllib3), as per CA Certificates — Advanced Usage — Requests 2.8.1 documentation:

  • requests ships with its own certificate bundle (but it can only be updated together with the module)
  • it will use (since requests v2.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.

Which, with today’s government-backed global hacking operations like Tailored Access Operations and the Great Firewall of China that target network infrastructure, is more probable than you think.


回答 4

不耐烦的是,禁用python未经验证的HTTPS警告的快速方法:

export PYTHONWARNINGS="ignore:Unverified HTTPS request"

For impatient, a quick way to disable python unverified HTTPS warning:

export PYTHONWARNINGS="ignore:Unverified HTTPS request"

回答 5

如果某些软件包供应商拥有自己的urllib3副本,则可接受的答案不起作用,在这种情况下,它仍然有效:

import warnings

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

The accepted answer doesn’t work if some package vendors it’s own copy of urllib3, in which case this will still work:

import warnings

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

回答 6

我的PyVmomi Client也有类似的问题。使用Python版本2.7.9,我用以下代码行解决了这个问题:

default_sslContext = ssl._create_unverified_context()
self.client = \
                Client(<vcenterip>, username=<username>, password=<passwd>,
                       sslContext=default_sslContext )

请注意,要使其正常工作,您至少需要Python 2.7.9。

I had a similar issue with PyVmomi Client. With Python Version 2.7.9, I have solved this issue with the following line of code:

default_sslContext = ssl._create_unverified_context()
self.client = \
                Client(<vcenterip>, username=<username>, password=<passwd>,
                       sslContext=default_sslContext )

Note that, for this to work, you need Python 2.7.9 atleast.


回答 7

为什么不使用pyvmomi 原始功能 SmartConnectNoSSL。他们添加了此函数June 14, 2016并为其命名ConnectNoSSL将名称更改为一天后SmartConnectNoSSL,使用它而不是通过项目中不必要的代码行传递警告?

提供一种无需SSL验证即可连接到指定服务器的标准方法。在使用自签名证书连接到服务器或希望完全忽略SSL时很有用

service_instance = connect.SmartConnectNoSSL(host=args.ip,
                                             user=args.user,
                                             pwd=args.password)

Why not using pyvmomi original function SmartConnectNoSSL. 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

service_instance = connect.SmartConnectNoSSL(host=args.ip,
                                             user=args.user,
                                             pwd=args.password)

回答 8

对于Python 2.7

将环境变量PYTHONWARNINGS作为键添加,并忽略相应的值,例如:

os.environ['PYTHONWARNINGS']="ignore:Unverified HTTPS request"

For Python 2.7

Add the environment variable PYTHONWARNINGS as key and the corresponding value to be ignored like:

os.environ['PYTHONWARNINGS']="ignore:Unverified HTTPS request"


bash:pip:找不到命令

问题:bash:pip:找不到命令

我下载了pip并运行python setup.py install,一切正常。本教程的下一步是运行,pip install <lib you want>但是甚至在尝试在线查找任何内容之前,我都会收到错误消息“ bash:pip:not found”。

这是在Mac OS X上,这也是我的新手,因此我假设有些路径设置在运行setup.py时未正确设置。我该如何进一步调查?我需要检查什么才能更好地了解问题的确切原因?

编辑:我也尝试过为Mac安装Python 2.7,希望友好的安装过程能够完成所有工作,例如编辑PATH,以及根据教程使一切正常工作所需的其他一切,但这是行不通的。安装运行后,“ python”仍然运行python 2.6,并且PATH未更新。

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.


回答 0

为什么不这样做,sudo easy_install pip或者这是否适用于python 2.6 sudo easy_install-2.6 pip

这将使用默认的python软件包安装程序系统安装pip,并同时为您节省了手动设置的麻烦。

这将允许您运行pippython软件包安装命令,因为它将与系统python一起安装。我也建议您在使用virtualenv软件包和模式时获得点子。:)

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:

sudo apt-get install python-setuptools

另外,对于python3,请使用easy_install3python3-setuptools

Use setuptools to install pip:

sudo easy_install pip

(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.


回答 2

首先:尝试使用pip3而不是pip。例:

pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

pip3应该与Python3.x一起自动安装。该文档尚未更新,因此例如在安装Flask时,将说明中的pip替换为pip3即可。

现在,如果这不起作用,则可能必须单独安装pip。

First of all: try pip3 instead of pip. Example:

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.


回答 3

更新:访问正确的pip安装以进行正确的python安装的一种更可靠的现代方法是使用语法python -m pip

原始答案

pip会将其自身安装到您的python安装位置的bin中。它还应创建一个指向更常见位置的符号链接,例如/usr/local/bin/pip

您可以编辑~/.profilePATH并将其更新为include /Library/Frameworks/Python.framework/Versions/2.6/bin,也可以在路径中的已知位置创建指向它的符号链接。

如果您执行以下操作: echo $PATH,您应该看到当前正在搜索的路径。如果/usr/local/bin位于PATH中,则可以执行以下操作:

ln -s /Library/Frameworks/Python.framework/Versions/2.6/bin/pip /usr/local/bin

我会选择将python bin添加到$ PATH变量中。

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:

ln -s /Library/Frameworks/Python.framework/Versions/2.6/bin/pip /usr/local/bin

I would opt for adding the python bin to your $PATH variable.


回答 4

按照给定安装Python最新版本 这里

它具有许多下载链接,例如numpy和scipy

然后转到终端并输入以下命令:

sudo easy_install pip

对于Python安装包,请检查此

安装软件包的要求本节介绍在安装其他Python软件包之前应遵循的步骤。

安装pip,setuptools和wheel如果从python.org安装了Python 2> = 2.7.9或Python 3> = 3.4,则已经具有pip和setuptools,但需要升级到最新版本:

在Linux或OS X上:

pip install -U pip setuptools在Windows上:

python -m pip install -U pip setuptools如果您正在Linux上使用由系统软件包管理器(例如“ yum”,“ apt-get”等)管理的Python安装,并且您想使用系统软件包管理器要安装或升级pip,请参阅使用Linux软件包管理器安装pip / setuptools / wheel

除此以外:

安全下载get-pip.py 1

运行python get-pip.py。2这将安装或升级点子。另外,如果尚未安装setuptools和wheel,它将安装setuptools和wheel。

Install Python latest version as given here

It has many download links like numpy and scipy

Then go to terminal and enter following command:-

sudo easy_install pip

For Python install packages check this

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

Otherwise:

Securely Download get-pip.py 1

Run python get-pip.py. 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.


回答 5

我必须承认对python绝对是新手,我只需要一件事:awscli。我在下载python 3.xx时遇到了这个问题-pip:命令未找到

遵循下载AWS CLI的说明后,我进行了更改

pip install awscli

pip3 install awscli

运行了正确的版本。

我在计算机上做了一个别名,以在输入python的同时运行python3,这通常会运行系统版本2.7。我现在不确定这是个好主意。我想我只是按照他们想要的那样输入命令

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


回答 6

请参阅“ 如何安装Pip”一文,以了解更多信息。

截至2019年,

提供下载get-pip.py https://pip.pypa.io使用下面的命令:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

使用以下命令运行get-pip.py:
sudo python get-pip.py

完成安装后,运行此命令以检查是否安装了pip。
pip --version

安装pip后,删除get-pip.py文件。
rm get-pip.py

Check out How to Install Pip article article for more information.

As of 2019,

Download get-pip.py provided by https://pip.pypa.io using the following command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Run get-pip.py using the following command:
sudo python get-pip.py

After you done installing, run this command to check if pip is installed.
pip --version

Remove get-pip.py file after installing pip.
rm get-pip.py


回答 7

使用apt-get安装会在整个系统范围内安装pip,而不仅仅是为您的用户安装本地系统。尝试使用此命令使pip在您的系统上运行…

$ sudo apt-get install python-pip python-dev build-essential

然后pip将被安装而没有任何问题,您将可以使用“ sudo pip …”。

Installing using apt-get installs a system wide pip, not just a local one for your user. Try this command to get pip running on your system …

$ sudo apt-get install python-pip python-dev build-essential

Then pip will be installed without any issues and you will be able to use “sudo pip…”.


回答 8

不推荐使用大多数安装PIP的方法。这是最新的(2019)解决方案。请下载get-pip脚本

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

运行脚本

sudo python get-pip.py

Most of the methods to install PIP are deprecated. Here is the latest (2019) solution. Please download get-pip script

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Run the script

sudo python get-pip.py

回答 9

我花了很长时间浏览本页上的所有答案,但在s-walsh对OP问题的评论中找到了一个对我有用的

答案是使用pip3:

$ pip3 install <name-of-install>

I spent ages going through all the answers on this page but found the one that worked for me in the comments of the OP question by s-walsh

The answer is to use pip3:

$ pip3 install <name-of-install>

回答 10

解决:

  1. 将此行添加到〜/ .bash_profile

    导出PATH =“ / usr / local / bin:$ PATH”

  2. 在终端窗口中,运行

    来源〜/ .bash_profile

To solve:

  1. Add this line to ~/.bash_profile

    export PATH=”/usr/local/bin:$PATH”

  2. In a terminal window, run

    source ~/.bash_profile


回答 11

它可能是root权限。我尝试退出root登录,使用

sudo su -l root
pip <command>

这对我行得通

It might be the root permission. I tried exit root login, use

sudo su -l root
pip <command>

that works for me


回答 12

安装Homebrew,打开Terminal或您喜欢的OSX终端仿真器并运行

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

将Homebrew目录插入PATH环境变量的顶部。您可以通过在〜/ .profile文件底部添加以下行来完成此操作

export PATH=/usr/local/bin:/usr/local/sbin:$PATH

现在,我们可以安装Python 2.7:

$ brew install python

获取点子存储库:

$ git clone https://github.com/pypa/pip

安装点:

$sudo easy_install pip

install Homebrew, open Terminal or your favorite OSX terminal emulator and run

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

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

export PATH=/usr/local/bin:/usr/local/sbin:$PATH

Now, we can install Python 2.7:

$ brew install python

Get pip repository:

$ git clone https://github.com/pypa/pip

install pip:

$sudo easy_install pip

回答 13

如果您正在运行Python 3.5,请运行以下终端命令:

sudo pip3 install -U nltk

终端中的任何其他pip命令都将类似:

pip3 install --upgrade pip
sudo pip3 install -U numpy ::

If you are running Python 3.5, run the following terminal command:

sudo pip3 install -U nltk

Any other pip commands in terminal would be similar:

pip3 install --upgrade pip
sudo pip3 install -U numpy ::

回答 14

python默认情况下安装它,但如果未安装,则可以使用以下cmd手动安装(仅适用于linux)

对于python3:

sudo apt install python3-pip 

对于python2

sudo apt install python-pip 

希望它的帮助。

python install it by default but if not install you can install it manual use following cmd (for linux only )

for python3 :

sudo apt install python3-pip 

for python2

sudo apt install python-pip 

hope its help.


回答 15

避免sudo

python <(curl https://bootstrap.pypa.io/get-pip.py) --user
echo 'export "PATH=$HOME/Library/Python/2.7/bin:$PATH"' >> ~/.bash_profile

从:

http://www.pip-command-not-found.com

Avoiding sudo:

python <(curl https://bootstrap.pypa.io/get-pip.py) --user
echo 'export "PATH=$HOME/Library/Python/2.7/bin:$PATH"' >> ~/.bash_profile

From:

http://www.pip-command-not-found.com


回答 16

CentOS 7用户可以使用:

yum install python-pip

virtualenv如果您使用的是点子,也建议使用。可以用相同的方式添加它:

yum install python-virtualenv

CentOS 7 users can just use:

yum install python-pip

Also recommend using virtualenv if you’re using pip. It can be added in the same way:

yum install python-virtualenv

回答 17

假设您有互联网,请参阅: https //pip.pypa.io/en/stable/installing/

基本上运行:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

python get-pip.py

assuming you have internet see: https://pip.pypa.io/en/stable/installing/

basically run:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

and

python get-pip.py

回答 18

(上下文:我的操作系统是使用AWS的Amazon linux。它看起来与RedHat类似,但看起来有所减少。)

退出外壳,然后打开一个新的外壳。pip命令现在可以使用。

这就是解决此位置问题的方法。

您可能还想知道:然后需要像下面的示例(例如jupyter)那样编写用于安装软件的pip命令,以便在我的系统上正常工作:

pip安装jupyter –user

具体来说,请注意缺少sudo以及–user的存在

如果pip文档对所有这些都说了话,那将是非常不错的,但是我猜这将需要输入更多的字符。

(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.


回答 19

不知道为什么以前没有提到过,但是唯一对我有用的(在我的NVIDIA Xavier上)是:

sudo apt-get install python3-pip

(或sudo apt-get install python-pip对于python 2)

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 

回答 21

问题似乎是您的python版本和要安装的库yoıu版本不匹配。例如:如果Django是Django3,而您的python版本是2.7,则可能会收到此错误。

“安装运行后,’python’仍运行Python 2.6,并且PATH未更新。”

1-安装最新版本的Python 2-手动将PATH更改为python38并进行比较。3-尝试重新安装。

我解决了此问题,方法是使用最新版本的Python手动替换PATH。对于Windows:; C:\ python38 \ Scripts

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


回答 22

我为克服这个问题所做的是sudo apt install python-pip

原来我的虚拟机尚未安装pip。可以想象其他人也可能有这种情况。

What I did to overcome this was sudo apt install python-pip.

It turned out my virtual machine did not have pip installed yet. It’s conceivable that other people could have this scenario too.


回答 23

python-pip在更新pip编辑后使用过时版本的pip(9.0),当前发布的pip版本为(18.0),请/usr/bin/pip替换此导入:

from pip import main

from pip._internal import main

这适用于pip 18.0问题是pip更改main功能名称重复为/usr/bin/pip3/usr/bin/pip2

还认为/usr/local/lib/[your_python_version]/dist-packages/pip/__main__.py它应该与/usr/bin/pip

python-pip use obsolete version of pip (9.0) current post pip version is (18.0) after updating pip edit /usr/bin/pip replace this import:

from pip import main

to

from pip._internal import main

this working for pip 18.0 problem is pip change main function name repeat for /usr/bin/pip3 and /usr/bin/pip2

also view /usr/local/lib/[your_python_version]/dist-packages/pip/__main__.py It should be the same as /usr/bin/pip


回答 24

请执行以下操作:

sudo apt update
sudo apt install python3-pip
source ~/.bashrc

这肯定会安装pip及其所有依赖项。PS这是用于python 3,如果要使用python 2,请从第二个命令中将python3替换为python

sudo apt install python-pip

Do following:

sudo apt update
sudo apt install python3-pip
source ~/.bashrc

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

sudo apt install python-pip

回答 25

要解决Mac中的“ bash:pip:找不到命令 ”问题

在Mac 1上发现两个版本是2.7,另一个是3.7

  • 当我说sudo easy_install pip时,pip在2.7下安装

  • 当我说sudo easy_install-3.7 pip时,pip已安装在3.7下

但是,每当我需要进行pip install时,我都想在python3.7下安装该软件包,因此我在.bash_profile中设置了一个别名(alias pip = pip3)。

所以现在,每当我进行pip install时,都会在python3.7下安装

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


回答 26

更新的安装命令为pip3

sudo apt-get install python3-pip

The updated command for installing pip3 is :

sudo apt-get install python3-pip