我正在尝试为我在Python中定期输入的命令保存一些按键.
在我的python启动脚本中,我定义了一个名为load的函数,它类似于import,但增加了一些功能.它需要一个字符串:
def load(s):
# Do some stuff
return something
Run Code Online (Sandbox Code Playgroud)
为了调用这个函数,我必须输入
>>> load('something')
Run Code Online (Sandbox Code Playgroud)
我宁愿能够简单地输入:
>>> load something
Run Code Online (Sandbox Code Playgroud)
我正在运行带有readline支持的Python ,所以我知道那里存在一些可编程性,但我不知道是否可以使用它.
我尝试通过InteractivConsole在我的启动文件中使用并创建它的实例来解决这个问题,如下所示:
import code, re, traceback
class LoadingInteractiveConsole(code.InteractiveConsole):
def raw_input(self, prompt = ""):
s = raw_input(prompt)
match = re.match('^load\s+(.+)', s)
if match:
module = match.group(1)
try:
load(module)
print "Loaded " + module
except ImportError:
traceback.print_exc()
return ''
else:
return s
console = LoadingInteractiveConsole()
console.interact("")
Run Code Online (Sandbox Code Playgroud)
这有点需要注意,我必须按两次Ctrl-D才能退出python解释器:一次退出我的自定义控制台,一次退出真正的控制台.
有没有办法在不编写自定义C程序并将解释器嵌入其中的情况下执行此操作?
在频道之外,我有建议将其附加到我的启动文件的末尾:
import sys
sys.exit()
Run Code Online (Sandbox Code Playgroud)
它运作良好,但我仍然对替代解决方案感兴趣.
我正在使用brew安装一些软件,当我尝试安装软件时,我得到了这个:
localhost:~ timger$ brew install autoconf
Error: No available formula for autoconf
localhost:~ timger$ brew install automake
Error: No available formula for automake
localhost:~ timger$ brew install libtool
Error: No available formula for libtool
localhost:~ timger$ brew install pkg-con
Run Code Online (Sandbox Code Playgroud) 该文档错误地声称
作为用户定义类实例的对象默认情况下可哈希化;他们都比较不相等(除了他们自己),他们的哈希值是
id()
尽管我记得这一次是对的,但是在当前版本的python(v2.7.10,v3.5.0)中,此类对象的哈希值等于其id显然是不正确的。
>>> class A:
... pass
...
>>> a = A()
>>> hash(a)
-9223372036578022804
>>> id(a)
4428048072
Run Code Online (Sandbox Code Playgroud)
在文档的另一部分中,据说哈希是从id 派生的。什么时候/为什么更改实现,哈希现在返回的数字如何“从” id派生?
我试图与调试的问题abc.ABCMeta-特别是子类的支票,并没有按预期方式工作,我想通过简单地添加一个启动print的__subclasscheck__方法(我知道有调试代码更好的方法,但假装的缘故这个问题别无选择)。但是,在 Python 崩溃之后启动 Python 时(如分段错误),我收到此异常:
Fatal Python error: Py_Initialize: can't initialize sys standard streams
Traceback (most recent call last):
File "C:\...\lib\io.py", line 84, in <module>
File "C:\...\lib\abc.py", line 158, in register
File "C:\...\lib\abc.py", line 196, in __subclasscheck__
RuntimeError: lost sys.stdout
Run Code Online (Sandbox Code Playgroud)
所以把它放在那里显然不是一个好主意print。但异常究竟从何而来?我只更改了 Python 代码,应该不会崩溃吧?
有人知道这个异常来自哪里以及我是否/如何避免它但仍然print在abc.ABCMeta.__subclasscheck__方法中放入一个?
我使用的是 Windows 10、Python-3.5(以防万一它可能很重要)。
我们为什么需要使用以下原因:
"test of split".split(" ")
Run Code Online (Sandbox Code Playgroud)
而且我们不能使用:
"test of split".split(sep=" ")
Run Code Online (Sandbox Code Playgroud)
当然,拆分是通过这种方式实现的(在C中)。但这真的意味着我们无法处理**kwargs用C编写的函数吗?
来自unicodedata文档:
unicodedata.digit(chr[, default]) 以整数形式返回分配给字符 chr 的数字值。如果没有定义这样的值,则返回默认值,或者,如果没有给出,则引发 ValueError。
unicodedata.numeric(chr[, default]) 返回分配给字符 chr 的数值作为浮点数。如果没有定义这样的值,则返回默认值,或者,如果没有给出,则引发 ValueError。
有人能解释一下这两个功能之间的区别吗?
在这里,可以阅读这两个函数的实现,但对我来说,与快速查看有什么区别并不明显,因为我不熟悉 CPython 实现。
编辑 1:
一个显示差异的例子会很好。
编辑2:
示例有助于补充@user2357112 的评论和精彩回答:
print(unicodedata.digit('1')) # Decimal digit one.
print(unicodedata.digit('?')) # ARABIC-INDIC digit one
print(unicodedata.digit('¼')) # Not a digit, so "ValueError: not a digit" will be generated.
print(unicodedata.numeric('?')) # Roman number two.
print(unicodedata.numeric('¼')) # Fraction to represent one quarter.
Run Code Online (Sandbox Code Playgroud) 我正在.pyd使用Visual Studio 2015 C ++项目和Python 2.7 32位构建Python扩展()。
这是我的.cpp文件:
#include <Python.h>
static PyObject* GetTwoInts(PyObject* self, PyObject* args)
{
srand(time(NULL));
int random1 = rand() % 10;
int random2 = rand() % 10;
PyObject * python_val = Py_BuildValue("ii", random1, random2);
return python_val;
}
static PyObject* GetListTwoInts(PyObject* self, PyObject* args)
{
srand(time(NULL));
int random1 = rand() % 10;
int random2 = rand() % 10;
PyObject *val1 = PyInt_FromLong(random1);
PyObject *val2 = PyInt_FromLong(random2);
PyObject *result = PyList_New(2);
PyList_SetItem(result, 0, val1);
PyList_SetItem(result, …Run Code Online (Sandbox Code Playgroud) 我试图在python中反转列表.那里有很多方法,[::-1]看起来很棒!但我很好奇怎么[::-1]办?它的时间复杂度是多少?
我在github中搜索了CPython repo,但我找不到任何线索.我的搜索策略是我搜索了关键词:::CPython repo.由于存在::python语法,即CPython源代码中[::-1]可能存在::,因此[::-1]可以引用它并进行反转.这有意义吗?
请注意,我这个问题仅供参考
我知道标题听起来像是查找内置Python函数的源代码的副本?.但让我解释一下.
比方说,我想找到类most_common方法的源代码collections.Counter.由于Counter该类是在python中实现的,我可以使用该inspect模块获取它的源代码.
即
>>> import inspect
>>> import collections
>>> print(inspect.getsource(collections.Counter.most_common))
Run Code Online (Sandbox Code Playgroud)
这将打印
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
因此,如果在C中实现的方法或类 …
当查看CPython时tokenizer.c,令牌生成器返回特定的错误消息。
例如,您可以看一下分词器尝试解析十进制数的部分。尝试解析该数字时,5_6一切都应该正常,但是当尝试解析该数字时5__6,令牌生成器应返回SyntaxError并显示消息“无效的十进制文字”:
static int
tok_decimal_tail(struct tok_state *tok)
{
int c;
while (1) {
do {
c = tok_nextc(tok);
} while (isdigit(c));
if (c != '_') {
break;
}
c = tok_nextc(tok);
if (!isdigit(c)) {
tok_backup(tok, c);
syntaxerror(tok, "invalid decimal literal");
return 0;
}
}
return c;
}
Run Code Online (Sandbox Code Playgroud)
使用Python,我尝试达到令牌生成器的SyntaxError消息:
In [12]: try:
...: eval('5__6')
...: except SyntaxError as e:
...: print(e.args, e.filename, e.lineno, e.msg, e.text)
('invalid token', ('<string>', 1, 2, '5__6')) …Run Code Online (Sandbox Code Playgroud) cpython ×10
python ×8
python-3.x ×3
c ×1
c++ ×1
hash ×1
homebrew ×1
interactive ×1
libtool ×1
list ×1
macos ×1
python-c-api ×1
readline ×1
split ×1
unicode ×1