小编Amr*_*Amr的帖子

thread.interrupt_main()在等待输入时不起作用

我已经读过这种技术来超时阻止IO操作,问题是它似乎不起作用.例如:

import thread, threading

def read_timeout(prompt, timeout=10.0):
    timer = threading.Timer(timeout, thread.interrupt_main)
    s = ''
    timer.start()

    try:
        s = raw_input(prompt)
    except KeyboardInterrupt:
        print 'operation timed out.'

    timer.cancel()
    return s

s = read_timeout('enter input: ')

if s:
    print 'you entered: %s' % s
Run Code Online (Sandbox Code Playgroud)

这不会在raw_input()返回之前中断主线程.任何帮助表示赞赏.

更新:

使用os.kill(os.getpid(), signal.SIGINT)而不是thread.interrupt_main()似乎工作(至少在Linux上,这不会给我我最初想要的可移植性).但是,我仍然想知道为什么上面的代码不起作用.

python multithreading timeout

6
推荐指数
1
解决办法
2101
查看次数

测试在循环内不会改变的条件

有时我必须检查一些在循环内没有变化的条件,这意味着在每次迭代中都会对测试进行评估,但我认为这不是正确的方法.

我认为,因为条件在循环内部没有变化,我应该只在循环外测试一次,但是我必须"重复自己"并且可能不止一次地写同一个循环.这是一个显示我的意思的代码:

#!/usr/bin/python

x = True      #this won't be modified  inside the loop
n = 10000000

def inside():
    for a in xrange(n):
        if x:    #test is evaluated n times
            pass
        else:
            pass

def outside():
    if x:        #test is evaluated only once
        for a in xrange(n):  
            pass
    else:
        for a in xrange(n):
            pass

if __name__ == '__main__':
    outside()
    inside()
Run Code Online (Sandbox Code Playgroud)

cProfile在前面的代码上运行给出了以下输出:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.542    0.542    0.542    0.542 testloop.py:5(inside)
        1    0.261    0.261    0.261    0.261 testloop.py:12(outside)
        1    0.000 …
Run Code Online (Sandbox Code Playgroud)

python optimization loops

6
推荐指数
2
解决办法
246
查看次数

Python C API - 使用比较函数导致'分段错误'

我目前正在尝试学习用C编写Python扩展,一切似乎进展顺利.但是,当我尝试使用比较功能时,它们都会导致Segmentaion故障.例如:

#include "Python.h"

int test(void) {
    int result;
    printf("Before compare...\n");
    result = PyObject_Compare(PyInt_FromLong(1), PyInt_FromLong(3));
    printf("result= %d\n", result);
    return 0;   
}
Run Code Online (Sandbox Code Playgroud)

test()从Python 执行(我使用ctypes)给出以下输出:

Before compare...
Segmentation fault
Run Code Online (Sandbox Code Playgroud)

对于其他比较函数,我发生这种情况,例如:PyObject_cmp......等

任何帮助表示赞赏,谢谢.

更多信息:

我首先将文件(test.c)编译为共享库:

$> python-config --cflags
-I/usr/include/python2.7 -I/usr/include/python2.7 -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes
$> python-config --ldflags
-L/usr/lib/python2.7/config -lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions

$> gcc -c $(python-config --cflags) ./test.c -o test.o
$> gcc -shared  ./test.o  $(python-config --ldflags) -o libtest.so
Run Code Online (Sandbox Code Playgroud)

然后我从Python开始这样的功能:

import ctypes
testlib …
Run Code Online (Sandbox Code Playgroud)

c python api

1
推荐指数
1
解决办法
641
查看次数

标签 统计

python ×3

api ×1

c ×1

loops ×1

multithreading ×1

optimization ×1

timeout ×1