我在 Anaconda 环境下使用 Python 3.3。
我想模拟 sqlite3.connect。例如在MyTests(见下文)中,我想test_sqlite3_connect返回字符串connection而不是实际sqlite3.Connection对象。
我试过修补它,但这不起作用。
from unittest.mock import patch
import unittest
import sqlite3
@patch('sqlite3.connect')
def sqlite3_connect(self,connection_string):
print('connect with : {0}'.format(connection_string))
return 'connection '
class MyTests(unittest.TestCase):
def test_sqlite3_connect(self):
print('testing connection')
dbc = DataBaseClass()
class DataBaseClass():
def __init__(self):
print('initialising database class')
self.connection = sqlite3.connect('test database')
Run Code Online (Sandbox Code Playgroud) 我有两个清单:
X = [True,False]
Y = [True,True]
Run Code Online (Sandbox Code Playgroud)
我试图将X [0]与Y [0]和X [1]与Y [1]进行比较.
我试过了
in [7]: X and Y
Out[7]: [True, True]
Run Code Online (Sandbox Code Playgroud)
但我期待的结果是[真,假].
我该怎么办?
我有一个Python函数.我想让它快得多吗?有人有任何提示吗?
def garchModel(e2, omega=0.01, beta=0.1, gamma=0.8 ):
sigma = np.empty( len( e2 ) )
sigma[0] = omega
for i in np.arange( 1, len(e2) ):
sigma[i] = omega + beta * sigma[ i-1 ] + gamma * e2[ i-1 ]
return sigma
Run Code Online (Sandbox Code Playgroud) 我正在使用 IPython 和 Cython。
我正在外部文本编辑器的模块中编辑我的 Cython 函数。
我想导入这些模块并在 IPython 中使用它们,但在导入时使用 IPython 编译它们。
这样做的语法是什么?我不希望我的代码在我的 IPython 笔记本中。
假设我有这样的函数:
def f():
x = np.arange(100)
return x[:5]
Run Code Online (Sandbox Code Playgroud)
f返回ay,这是x上的视图.
x还会在后台使用内存吗?
我需要在Python中获得每个月的第二个星期五.
我写了下面的函数来演示我需要的东西.但是,我想知道是否有更优雅的方式使用Pandas的date_range功能和适当的偏移来做到这一点.
def second_friday_of_month_date_range( start, end ):
dr = pd.date_range( start, end, freq='MS' )
first_weekday_of_month_to_2nd_friday_of_month = np.array( [ 12, 11, 10, 9, 8, 14, 13 ], dtype=int )
wd = first_weekday_of_month_to_2nd_friday_of_month[ dr.weekday ]
offsets = [ datetime.timedelta( days=int(x)-1 ) for x in wd ]
dts = [d+o for d, o in zip( dr, offsets)]
return pd.DatetimeIndex( dts )
import pandas as pd
import datetime
d0 = datetime.datetime(2016,1,1)
d1 = datetime.datetime(2017,1,1)
dr = second_friday_of_month_date_range( d0, d1 )
print( dr …Run Code Online (Sandbox Code Playgroud) 我有一个作为服务运行的Python脚本.它写入磁盘.如果用户在服务上调用systemctl stop,我想以自己的方式处理该命令以降低文件损坏的风险.
如何捕获systemctl stop命令?
我在/ usr/lib/systemd/system中的文件是:
[Unit]
Description=foo
[Service]
Type=simple
ExecStart=/usr/bin/python /srv/go.py
User=jon
Restart=always
[Install]
WantedBy=graphical.target
Run Code Online (Sandbox Code Playgroud)
我的Python脚本是:
#!/usr/bin/python
import time
import datetime
import threading
def worker():
while True:
with open('/tmp/go.txt', 'a') as f:
s = str(datetime.datetime.utcnow()) + '\n'
f.write(s)
print(s)
time.sleep(1)
if __name__=='__main__':
t = threading.Thread(target=worker)
t.start()
Run Code Online (Sandbox Code Playgroud) 操作是tf.group()按顺序执行的吗?
如果它们没有按顺序执行,是否有类似的操作使它们按顺序运行?或者有一个干净的方式来按顺序运行它们?
我的目标是一次又一次地运行操作A和B,即
sess.run(A)
sess.run(B)
sess.run(A)
sess.run(B)
sess.run(A)
sess.run(B)
sess.run(A)
sess.run(B)
...
Run Code Online (Sandbox Code Playgroud) 我在Python中使用了很多argmin和argmax.
不幸的是,功能很慢.
我做了一些搜索,我能找到的最好的是:
http://lemire.me/blog/archives/2008/12/17/fast-argmax-in-python/
def fastest_argmax(array):
array = list( array )
return array.index(max(array))
Run Code Online (Sandbox Code Playgroud)
不幸的是,这个解决方案仍然只有np.max的一半,我想我应该能找到与np.max一样快的东西.
x = np.random.randn(10)
%timeit np.argmax( x )
10000 loops, best of 3: 21.8 us per loop
%timeit fastest_argmax( x )
10000 loops, best of 3: 20.8 us per loop
Run Code Online (Sandbox Code Playgroud)
请注意,我将此应用于Pandas DataFrame Groupby
例如
%timeit grp2[ 'ODDS' ].agg( [ fastest_argmax ] )
100 loops, best of 3: 8.8 ms per loop
%timeit grp2[ 'ODDS' ].agg( [ np.argmax ] )
100 loops, best of 3: 11.6 ms per …Run Code Online (Sandbox Code Playgroud) 我有一个非常简单的 cython 模块,名为empty_test.pyx:
cimport numpy as cnp
cpdef return_empty():
return cnp.empty(0, dtype=np.int32)
Run Code Online (Sandbox Code Playgroud)
当我尝试运行时,出现return_empty此错误:
empty_test.pyx:5:14: cimported module has no attribute 'empty'
Run Code Online (Sandbox Code Playgroud)
这是我的setup.py文件:
from distutils.core import setup
from Cython.Build import cythonize
import numpy as np
setup(
ext_modules=cythonize(['empty_test.pyx'],
),
include_dirs = [np.get_include()],
)
Run Code Online (Sandbox Code Playgroud)
我知道我可以尝试import numpy as np代替cimport numpy as np,但我正在尝试使用 numpy 代码的 C 版本。
python ×7
numpy ×4
cython ×2
anaconda ×1
datetime ×1
indexing ×1
ipython ×1
linux ×1
pandas ×1
python-3.x ×1
systemd ×1
tensorflow ×1
unit-testing ×1