我有py.test运行的多个测试,它们位于多个文件的多个类中.
共享一个大字典的最简单的方法是什么 - 我不想复制 - py.test使用的每个文件中每个类的每个方法?
简而言之,我需要为每个测试制作一个"全局变量".在py.test之外,我没有使用这个变量,所以我不想将它存储在被测试的文件中.我经常使用py.test的灯具,但这似乎有点过分了.也许这是唯一的方法?
背景:我有一个Python程序几个紧密的循环被一再呼吁,其中包括datetime.datetime.now()
方法,还有datetime.datetime.min
和datetime.datetime.max
属性.为了优化,我想将它们导入到本地命名空间,避免重复的,不必要的模块层次结构名称查找,如下所示:
from datetime.datetime import now, min, max
Run Code Online (Sandbox Code Playgroud)
然而,Python抱怨:
Traceback (most recent call last):
File "my_code.py", line 1, in <module>
from datetime.datetime import now, min, max
ImportError: No module named datetime
Run Code Online (Sandbox Code Playgroud)
问题: 为什么上述子模块导入不起作用?
解决方法: 我可以这样做:
import datetime
dt_now = datetime.datetime.now
dt_min = datetime.datetime.min
dt_max = datetime.datetime.max
Run Code Online (Sandbox Code Playgroud)
但是,我很好奇为什么更传统的方法不起作用?为什么我不能直接从datetime.dateime子模块导入方法和属性?...并且,有没有理由避免上述解决方法(除了可读性,超越自己等)?
谢谢!
我试图了解是否可以使用bash脚本读取容器的元数据(特别是标签)属性.
例如,如果有一个Dockerfile,如:
FROM busybox
LABEL abc = abc_value1
Run Code Online (Sandbox Code Playgroud)
而且,如果我基于上面的文件构建并运行图像,如下所示:
docker build . -t image1
docker run -ti image1 /bin/bash
Run Code Online (Sandbox Code Playgroud)
有没有办法在bash shell中访问"abc"标签的值?如果是这样,怎么样?
我编写了一个Linux内核模块,作为基于Freescale P2020RDB的定制板的FPGA驱动程序.驱动程序包含几个#defines
指定各种地址,大小,总线宽度等.我想从驱动程序中访问板的扁平化设备树(FDT)来配置这些地址,因此驱动程序可以用于其他板,其中FPGA具有不同的大小或驻留在不同的地址.
我在模块的初始化函数中添加了以下简单代码,这是我在浏览Linux内核源代码树时找到的代码:
...
#include <linux/of_device.h>
#include <linux/of_platform.h>
static int __init fpga_init(void) {
struct device_node *dt_node;
const u8 *property;
int len;
printk(KERN_INFO "(I) FPGA module loaded at 0x%p\n", fpga_init);
dt_node = of_find_node_by_path("/fpga_dt@c0000000");
if (!dt_node) {
printk(KERN_ERR "(E) Failed to find device-tree node: /fpga_dt@c0000000\n");
return -ENODEV;
}
printk(KERN_INFO "(I) Found device-tree node. Now retrieving property.\n");
property = of_get_property(dt_node, "reg", &len);
printk(KERN_INFO "(I) reg=0x%08lX\n", (unsigned long) property[0]);
...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,插入模块会在尝试查找设备节点时产生分段错误.
# insmod fpga_drv.ko
(I) FPGA module loaded at …
Run Code Online (Sandbox Code Playgroud) linux linux-device-driver linux-kernel embedded-linux device-tree
问: 什么是可比的解决方案的例子,在这个环节,除了使用实施GEVENT-socketio和Socket.io.js与瓶?我正在寻找最小的解决方案,它将简单地将一些流量从客户端传递到服务器并使用gevent-socketio,Socket.io.js和bottle返回客户端.
背景:我开发了一个简单的Web应用程序,它为服务器上的远程自定义shell(cli)提供基于Web的终端.浏览器(客户端)从表单输入字段收集shell命令,通过Web套接字将命令传递给gevent.pywsgi.WSGIServer
通过geventwebsocket.WebSocketHandler
处理程序处理请求,处理程序将命令提供给shell,同时通过套接字将输出异步返回到textarea字段在客户端浏览器中的表单中.这是基于瓶子团队提供的一个很好的例子:
http://bottlepy.org/docs/dev/async.html#finally-websockets
这里提供冗余:
example_server.py:
from bottle import request, Bottle, abort
app = Bottle()
@app.route('/websocket')
def handle_websocket():
wsock = request.environ.get('wsgi.websocket')
if not wsock:
abort(400, 'Expected WebSocket request.')
while True:
try:
message = wsock.receive()
wsock.send("Your message was: %r" % message)
except WebSocketError:
break
from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketHandler, WebSocketError
server = WSGIServer(("0.0.0.0", 8080), app,
handler_class=WebSocketHandler)
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)
client.html:
<!DOCTYPE html>
<html>
<head>
<script …
Run Code Online (Sandbox Code Playgroud) 我想将命令行参数传递给py.test来创建夹具.例如,我想将数据库主机名传递给下面的夹具创建,因此它不会被硬编码:
import pytest
def pytest_addoption(parser):
parser.addoption("--hostname", action="store", default='127.0.0.1', help="specify IP of test host")
@pytest.fixture(scope='module')
def db(request):
return 'CONNECTED TO [' + request.config.getoption('--hostname') + '] SUCCESSFULLY!'
def test_1(db):
print db
assert 0
Run Code Online (Sandbox Code Playgroud)
不幸的是,如果从命令行中省略了参数,则不设置默认值:
$ py.test test_opt.py
=================================================================== test session starts ====================================================================
platform linux2 -- Python 2.7.5 -- pytest-2.3.5
collected 1 items
test_opt.py E
========================================================================== ERRORS ==========================================================================
_________________________________________________________________ ERROR at setup of test_1 _________________________________________________________________
request = <FixtureRequest for <Module 'test_opt.py'>>
@pytest.fixture(scope='module')
def db(request):
> return 'CONNECTED TO [' + request.config.getoption('--hostname') + '] …
Run Code Online (Sandbox Code Playgroud) Web上有几个教程,记录了如何使用一些基本的黑客攻击和修补来为各种嵌入式系统交叉编译或交叉构建Python,如下所示:
http://randomsplat.com/id5-cross-compiling-python-for-embedded-linux.html
在我使用Python 2.7.2时,这对我来说效果很好.
在Python 2.7.4中,一些交叉编译功能最终包含在上游构建过程中,在此处记录:
这打破了所有以前的交叉构建攻击,我找不到任何更新的教程或文档,用于新的内置交叉编译过程.
有没有人在2.7 2.7分支中使用新的交叉编译过程以及在2.7分支中有一个很好的示例或文档?
谢谢!
如果我在Python 2.7中有一个非常简单(尽管可能非常复杂)的函数生成器,就像这样:
def accumulator():
x = yield 0
while True:
x += yield x
Run Code Online (Sandbox Code Playgroud)
哪个可以使用,如下所示:
>>> a = accumulator()
>>> a.send(None)
0
>>> a.send(1)
1
>>> a.send(2)
3
>>> a.send(3)
6
Run Code Online (Sandbox Code Playgroud)
除了乘以2之外,另一个产生相同结果的函数生成器的简单包装器是什么?上面的函数生成器很简单,但请假设复制粘贴太复杂.我正在尝试一些事情,比如:
def doubler():
a = accumulator()
a.send(None)
y = yield 0
while True:
y = 2 * a.send(yield y)
Run Code Online (Sandbox Code Playgroud)
或者,想象一些更简单的事情:
def doubler():
a = accumulator()
a.send = lambda v: 2 * super(self).send(v)
return a
Run Code Online (Sandbox Code Playgroud)
两者都是可怕的破坏,所以我不会分享语法错误,但它可以说明我正在尝试做什么.
理想情况下,我想得到一些东西,比如:
>>> d = doubler()
>>> d.send(None)
0
>>> d.send(1)
2
>>> d.send(2)
6 …
Run Code Online (Sandbox Code Playgroud) 我有一个表行,在表格行的任何地方都有鼠标点击附加的Javascript操作:
<tr onmousedown="someAction(this)">
<td>cell 1</td>
<td>cell 2</td>
<td><a href="page2.html">cell 3</a></td>
</tr>
Run Code Online (Sandbox Code Playgroud)
如果用户点击该行中的任何位置,我希望遵循Javascript操作someAction(this).但是,如果用户单击指向page2的链接,那么我希望忽略该操作并遵循链接.
不幸的是,首先会观察到该动作,这恰好会使链接文本的位置移动到足以使点击被删除.换句话说,在这种情况下,用户实际上无法点击链接并转到第2页.
如何禁用链接点击的mousedown操作?
谢谢!
更新: 基于答案,我最终在HTML的末尾包含了以下JavaScript,它按照建议注册了一个停止传播的事件处理程序,如下所示:
...
<script type="text/javascript" language="javascript">
//<![CDATA[
function stopEvent(ev) {
ev.stopPropagation();
}
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("onmousedown", stopEvent, false);
}
//]]>
</html>
Run Code Online (Sandbox Code Playgroud)
这可能很容易被包含在文档的onload事件中,但CDATA部分已经因其他原因而被要求,所以我在这里添加了我需要的内容.
感谢所有的帮助和好建议!:)
我正在为 web 应用程序使用带有cherrypy(它提供 WSGI)的瓶子。CherryPy 在此设置中不记录 Web 访问。目前,我几乎正在使用 Bottle 的hook 插件记录所有内容,如下所示:
import bottle
from bottle import route, static_file, get, post, error, request, template, redirect, response, hook
@hook('after_request')
def log_after_request():
try:
length = response.content_length
except:
try:
length = len(response.body)
except:
length = '???'
print '{ip} - - [{time}] "{method} {uri} {protocol}" {status} {length}'.format(
ip=request.environ.get('REMOTE_ADDR'),
time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
method=request.environ.get('REQUEST_METHOD'),
uri=request.environ.get('REQUEST_URI'),
protocol=request.environ.get('SERVER_PROTOCOL'),
status=response.status_code,
length=length,
)
@route('/index.html')
def index_handler():
return '<h1>Hello, world!</h1>'
app = bottle.default_app()
bottle.run(host='0.0.0.0', port='80', app=app, server='cherrypy', request_queue_size=300, debug=True)
Run Code Online (Sandbox Code Playgroud)
这会向 …
python ×7
bottle ×2
pytest ×2
python-2.7 ×2
bash ×1
cherrypy ×1
datetime ×1
device-tree ×1
docker ×1
dockerfile ×1
generator ×1
gevent ×1
import ×1
javascript ×1
linux ×1
linux-kernel ×1
logging ×1
socket.io ×1
testing ×1
unit-testing ×1
websocket ×1