您无法使用正则表达式来做到这一点,并且您可能不想编写自己的 ecma-standard262 实现(这完全是多余的)。
至于我正在挖掘 Microsoft 的 V8 JavaScript 引擎,更具体地说是 PyV8。 我建议你可以使用它。
如果您遇到问题,这是我用来安装的代码(pip install 是我的 64 位系统上的一个错误,所以我使用了源代码):
apt-get install subversion scons libboost-python-dev
svn checkout http://v8.googlecode.com/svn/trunk/ v8
svn checkout http://pyv8.googlecode.com/svn/trunk/ pyv8
cd v8
export PyV8=`pwd`
cd ../pyv8
sudo python setup.py build
sudo python setup.py install
我记得这些命令,这并不是我的错。 (我复制粘贴了javascript解析文件,但是有效)
问题本身的答案:
一个更复杂的 Hello World 国际示例javascript解析文件,枚举全局对象的一些变量:
import PyV8
class Global(PyV8.JSClass): # define a compatible javascript class
def hello(self): # define a method
print "Hello World"
def alert(self, message): # my own alert function
print type(message), ' ', message
@property
def GObject(self): return self
def __setattr__(self, key, value):
super(Global, self).__setattr__(key, value)
print key, '=', value
G = Global()
ctxt = PyV8.JSContext(G)
ctxt.enter()
ctxt.eval("var a=hello; GObject.b=1.0; a();")
list_all_cmd = '''for (myKey in GObject){
alert(GObject[myKey]);
}'''
ctxt.eval(list_all_cmd)
ctxt.leave()
(在浏览器中,您应该调用全局对象 -window)
该代码将输出:
b = 1
Hello World
function() { [native code] }
1
function() { [native code] }
function() { [native code] }
function() { [native code] }
function() { [native code] }
function() { [native code] }
function() { [native code] }
function() { [native code] }
function() { [native code] }