假设如下:
def MyFunc(a):
if a < 0:
return None
return (a+1, a+2, a+3)
v1, v2, v3 = MyFunc()
# Bad ofcourse, if the result was None
Run Code Online (Sandbox Code Playgroud)
定义一个返回元组的函数的最佳方法是什么,但是可以很好地调用它.目前,我可以这样做:
r = MyFunc()
if r:
v1, v2, v3 = r
else:
# bad!!
pass
Run Code Online (Sandbox Code Playgroud)
我不喜欢这个是我必须使用单个变量然后解压缩它.
另一个解决方案是我可以让函数返回一个充满Nones的元组,这样调用者可以很好地解压....
任何人都可以建议更好的设计?
是否有可能写一个#define定义了#define?
例如:
#define FID_STRS(x) #x
#define FID_STRE(x) FID_STRS(x)
#define FID_DECL(n, v) static int FIDN_##n = v;static const char *FIDS_##n = FID_STRE(v)
Run Code Online (Sandbox Code Playgroud)
但反而:
#define FID_DECL2(n, v) #define FIDN_##n v \
FIDS_##n FID_STRE(v)
Run Code Online (Sandbox Code Playgroud)
FID_DECL工作正常,但创建两个静态变量.是否有可能做出FID_DECL2工作并定义两个定义?
PyObject* PyImport_ImportModule( const char *name)
Run Code Online (Sandbox Code Playgroud)
如何指定完整的文件路径和模块名称?
喜欢PyImport_SomeFunction(const char *path_to_script, const char *name)。
我有这个代码在Python 2.5中运行良好,但在2.7中没有:
import sys
import traceback
try:
from io import StringIO
except:
from StringIO import StringIO
def CaptureExec(stmt):
oldio = (sys.stdin, sys.stdout, sys.stderr)
sio = StringIO()
sys.stdout = sys.stderr = sio
try:
exec(stmt, globals(), globals())
out = sio.getvalue()
except Exception, e:
out = str(e) + "\n" + traceback.format_exc()
sys.stdin, sys.stdout, sys.stderr = oldio
return out
print "%s" % CaptureExec("""
import random
print "hello world"
""")
Run Code Online (Sandbox Code Playgroud)
我得到:
string argument expected, got 'str' Traceback (most recent call last): File "D:\3.py", line 13, …
我不确定这是否是调用函数的最佳方法before和after函数f1().
class ba(object):
def __init__(self, call, before, after):
self.call = call
self.before = before
self.after = after
def __call__(self, *args):
self.before()
r = self.call(*args)
self.after()
return r
class test1(object):
def mybefore(self):
print "before func call"
def myafter(self):
print "after func call"
def meth1(a1, a2):
print "meth1(a1=%d, a2=%d)" % (a1, a2)
t = test1()
wmeth1 = ba(meth1, t.mybefore, t.myafter)
wmeth1(1, 2)
Run Code Online (Sandbox Code Playgroud)
请指教.
我需要根据输入字符串"s"调用exec()或eval()
如果"s"是一个表达式,在调用eval()之后,如果结果不是None,我想打印结果
如果"s"是一个声明,则只需执行exec().如果声明恰好打印出来的东西那么就是这样吧.
s = "1 == 2" # user input
# ---
try:
v = eval(s)
print "v->", v
except:
print "eval failed!"
# ---
try:
exec(s)
except:
print "exec failed!"
例如,"s"可以是:
s = "print 123"
在这种情况下,应该使用exec().
当然,我不想先尝试eval(),如果失败则调用exec()
我无法使用线程,因此我想编写一个服务器程序,该程序可能会在一段时间后中断:
d = show_non_modal_dialog(“为客户服务”)
s =套接字(...)
s.bind(...)
s.listen()
同时(!user_pressed_cancel())
{
s.accept()#定时接受大约1秒钟
如果timed_out:
继续
serve_client
close_client_sock
}
hide_non_modal_dialog(d)
python ×6
c ×1
callable ×1
detect ×1
exec ×1
expression ×1
nonblocking ×1
python-c-api ×1
redirect ×1
return ×1
sockets ×1
stdio ×1
stringio ×1
tuples ×1