以下在Python 3中执行时没有错误:
code = """
import math
def func(x):
return math.sin(x)
func(10)
"""
_globals = {}
exec(code, _globals)
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试捕获局部变量dict,它也会失败NameError:
>>> _globals, _locals = {}, {}
>>> exec(code, _globals, _locals)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-aeda81bf0af1> in <module>()
----> 1 exec(code, {}, {})
<string> in <module>()
<string> in func(x)
NameError: name 'math' is not defined
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况,如何在捕获全局变量和局部变量时执行此代码?
是否有任何python大师能够解释为什么这段代码不起作用:
def f(code_str):
exec(code_str)
code = """
g = 5
x = [g for i in range(5)]
"""
f(code)
Run Code Online (Sandbox Code Playgroud)
错误:
Traceback (most recent call last):
File "py_exec_test.py", line 9, in <module>
f(code)
File "py_exec_test.py", line 2, in f
exec(code_str)
File "<string>", line 3, in <module>
File "<string>", line 3, in <listcomp>
NameError: name 'g' is not defined
Run Code Online (Sandbox Code Playgroud)
虽然这个工作正常:
code = """
g = 5
x = [g for i in range(5)]
"""
exec(code)
Run Code Online (Sandbox Code Playgroud)
我知道它与locals和globals有关,就好像我从我的主范围传递exec函数locals和globals它工作正常,但我不完全理解发生了什么.
这可能是Cython的一个错误吗?
编辑:尝试使用python 3.4.0和python 3.4.3
是否有可能import一个Python模块从过使用互联网http(s), ftp,smb或任何其它协议?如果是这样,怎么样?如果没有,为什么?
我想这是为了让Python使用更多的协议(读取文件系统)并使其能够使用其他协议.是的我同意它会慢很多倍,但是一些优化和更大的未来带宽肯定会平衡它.
例如:
import site
site.addsitedir("https://bitbucket.org/zzzeek/sqlalchemy/src/e8167548429b9d4937caaa09740ffe9bdab1ef61/lib")
import sqlalchemy
import sqlalchemy.engine
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 PyQt5 构建计算器,我得到了需要评估的字符串并将其分配给一个变量,以便我可以将该变量作为答案传递给小部件。到目前为止,我可以评估表达式但不能评估它。我怎样才能做到这一点 ?到目前为止,我有以下代码:-
# this functions gets called when Enter is pressed
def etrp(self):
eqn = self.sender().text() #I get string like '23+4'
eqn1 = "{0} = {1}".format("global x",eqn) #I make it x = 23+4
x = 0
exec(eqn1) # I get error here
print(x)
#some code .....
Run Code Online (Sandbox Code Playgroud)
当我尝试在没有全局的情况下运行它时,它运行没有错误,但 x 仍然为 0,如果我像这样运行它,我会收到此错误:-
qt5ct: using qt5ct plugin
global x = 12+32
Traceback (most recent call last):
File "/home/orayan/Development/Python/Calculator/calculator.py", line 11, in etrp
exec(eqn1)
File "<string>", line 1
global x = 12+32 …Run Code Online (Sandbox Code Playgroud) 有人能想出一个使用 exec 的良好实践示例吗?
如果总有一种更高效、更安全的方法来替代 exec,为什么 python 不弃用 exec?
好的,所以我在一个工具的配置脚本是exec'python脚本' 的环境中工作.exec调用是这样的:
outer.py:
exec(open("inner.py").read(), globals(), {})
Run Code Online (Sandbox Code Playgroud)
现在,我想在exec'd脚本中做一些相对基本的迭代.在这种情况下,当某些值不在白名单中时执行工作:
inner.py:
items = (
'foo/bar',
'foo/baz',
'foof',
'barf/fizz',
)
whitelist = (
'foo/',
)
for key in items:
try:
# Not terribly efficient, but who cares; computers are fast.
next(True for prefix in whitelist if key.startswith(prefix))
# Do some work here when the item doesn't match the whitelist.
except StopIteration:
print("%10s isn't in the whitelist!" % key)
Run Code Online (Sandbox Code Playgroud)
运行python inner.py产生预期结果:
foof isn't in the whitelist!
barf/fizz isn't in …Run Code Online (Sandbox Code Playgroud) 在python3中,当我运行时
>>> exec("","","")
TypeError: exec() arg 2 must be a dict, not str
>>> exec( "print('Hello')", print("World"), print("!") )
World
!
Hello
>>> type(print("World"))
World
<class 'NoneType'>
Run Code Online (Sandbox Code Playgroud)
我的意思是在Python3中,exec()的arg2需要一个dict,但我们仍然可以放一个不是dict的print()函数.为什么?