def main(): with codecs.open("esp.js", "r", "utf-8") as f: d = f.read() r = js2py.translate_js(d) exec r in {} with open('res.py', 'wb') as f2: f2.write(r)
def main(): with codecs.open("esp.js", "r", "utf-8") as f: d = f.read() r = js2py.translate_js(d) exec r in {} with open('res.py','wb') as f2: f2.write(r)
def compile(self, source, context=None, environment=None, **keywords): if context is None: header = "" else: header = "__package__=\"%s\"\n" % ":".join((managers.engine.application.id, context)) with self._lock: source_in_python = js2py.translate_js(source, header) return compile(source_in_python, self.SIGNATURE, "exec")
def main(): with requests.get( 'https://www.avito.ru/s/cc/' '0cfed52cab4c417618b16cf145dfa467b3180549.js', ) as r: python = js2py.translate_js(r.text) # with open('secret.js', 'rt') as f: # content = f.read() # # python = js2py.translate_js(content) # # context = js2py.EvalJs({ # # 'decodeURI': unquote, # # }) # # f = context.(content) print(python)
def create_code_for_nearley_grammar(g, start, builtin_path, folder_path, es6=False): import js2py emit_code = [] def emit(x=None): if x: emit_code.append(x) emit_code.append('\n') js_code = ['function id(x) {return x[0];}'] n2l = NearleyToLark() rule_defs = _nearley_to_lark(g, builtin_path, n2l, js_code, folder_path, set()) lark_g = '\n'.join(rule_defs) lark_g += '\n' + '\n'.join('!%s: %s' % item for item in n2l.extra_rules.items()) emit('from lark import Lark, Transformer') emit() emit('grammar = ' + repr(lark_g)) emit() for alias, code in n2l.alias_js_code.items(): js_code.append('%s = (%s);' % (alias, code)) if es6: emit(js2py.translate_js6('\n'.join(js_code))) else: emit(js2py.translate_js('\n'.join(js_code))) emit('class TransformNearley(Transformer):') for alias in n2l.alias_js_code: emit(" %s = var.get('%s').to_python()" % (alias, alias)) emit(" __default__ = lambda self, n, c, m: c if c else None") emit() emit('parser = Lark(grammar, start="n_%s", maybe_placeholders=False)' % start) emit('def parse(text):') emit(' return TransformNearley().transform(parser.parse(text))') return ''.join(emit_code)
def run(src: str) -> None: with open(src) as rf: source = rf.read() print(js2py.translate_js(source)) # Redefine builtin objects... Do you have a better idea? if "js2py" in sys.modules: del sys.modules["js2py"] # del js2py.pyjs # del js2py from js2py.pyjs import Scope, JS_BUILTINS, set_global_object, Js # setting scope var = Scope(JS_BUILTINS) set_global_object(var) # Code follows: var.registers([u'$']) var.put(u'$', Js(5.0))
import js2py import datetime now = datetime.datetime.now # the line below will # - build a 'compilation plan' by substituting strings and constants with placeholders # - then build the ast and emit the python code from that compilation plan # - then substitute back in the constants # This causes some regex overhead, but for js code with similar structure # subsequent translate_js calls are 20 times faster js2py.translate_js('name == "Robert" && age == 46', use_compilation_plan=True) # this lines below will re-use the compilation plan already laid out by the # statement above js2py.translate_js('name == "Guido" && age == 50', use_compilation_plan=True) js2py.translate_js('name == "Spam" && age == 25', use_compilation_plan=True) # now we'll show off the performance gain: start = now() for cnt in range(10000): js2py.translate_js('name == "Robert" && age == %i' % cnt, use_compilation_plan=False) print(('duration without compilation plan %i' % (now() - start).seconds)) start = now() for cnt in range(10000): js2py.translate_js('name == "Robert" && age == %i' % cnt, use_compilation_plan=True) print(('duration with compilation plan %i' % (now() - start).seconds))
URL = "https://fanyi.baidu.com/translate" # SESS = requests.Session() SESS = requests_cache.CachedSession( cache_name=CACHE_NAME, expire_after=EXPIRE_AFTER, allowable_methods=('GET', 'POST'), ) SESS.hooks = { 'response': make_throttle_hook(1, 200) } # to play safe, default: 0.67, 1000 SESS.get(URL, headers=HEADERS) # for js_sign below exec(js2py.translate_js(JS)) # pylint: disable=exec-used def js_sign(text, gtk='320305.131321201'): '''gtk, does not play role >>> assert js_sign('test') == '431039.159886' ''' return PyJs_anonymous_1_(text, gtk).to_py() # pylint: disable=undefined-variable def jp_match(path, obj): '''emulate jsonpath_rw_ext\'s jp.match''' return [elm.value for elm in parse(path).find(obj)]
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; // For convenience... Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); }; today = new Date(4393494334343434); today.toISOString ''' #c.execute(a) res = js2py.translate_js(a) with open('test_res.py', 'wb') as f: f.write(res) def f(a, b, c): return [xrange(100),0] print js2py.eval_js(a) e = js2py.EvalJs() e.a = [1,2,3] e.f = f a = e.f() #print a[0]
def require(module_name, cache_folder='.', suffix='_pyq', update=False, fLOG=noLOG): """ Modified version of function *require* in `node_import.py <https://github.com/PiotrDabkowski/Js2Py/blob/master/js2py/node_import.py>`_. @param module_name required library name @param cache_folder location of the files the function creates @param suffix change the suffix if you use the same folder for multiple files @param update update the converted script @param fLOG logging function @return outcome of the javascript script The function is not fully tested. """ if module_name.endswith('.js'): raise ValueError("module_name must the name without extension .js") global _require_cache if module_name in _require_cache and not update: py_code = _require_cache[module_name] else: from js2py.node_import import ADD_TO_GLOBALS_FUNC, GET_FROM_GLOBALS_FUNC from js2py import translate_js py_name = module_name.replace('-', '_') module_filename = '%s.py' % py_name full_name = os.path.join(cache_folder, module_filename) var_name = py_name.rpartition('/')[-1] in_file_name = os.path.join( cache_folder, "require_{0}_in{1}.js".format(module_name, suffix)) out_file_name = os.path.join( cache_folder, "require_{0}_out{1}.js".format(module_name, suffix)) code = ADD_TO_GLOBALS_FUNC code += """ var module_temp_love_python = require('{0}'); addToGlobals('{0}', module_temp_love_python); """.format(module_name) with open(in_file_name, 'w', encoding='utf-8') as f: f.write(code) pkg_name = module_name.partition('/')[0] install_node_js_modules(cache_folder, [pkg_name], fLOG=fLOG) inline_script = "(require('browserify')('%s').bundle(function (err,data)" + \ "{fs.writeFile('%s',require('babel-core').transform(data," + \ "{'presets':require('babel-preset-es2015')}).code,()=>{});}))" inline_script = inline_script % (in_file_name.replace( "\\", "\\\\"), out_file_name.replace("\\", "\\\\")) run_js_with_nodejs(inline_script, fLOG=fLOG, path_dependencies=cache_folder) with open(out_file_name, "r", encoding="utf-8") as f: js_code = f.read() js_code += GET_FROM_GLOBALS_FUNC js_code += ";var {0} = getFromGlobals('{1}');{0}".format( var_name, module_name) fLOG('[require] translating', out_file_name) py_code = translate_js(js_code) with open(full_name, 'w', encoding="utf-8") as f: f.write(py_code) _require_cache[module_name] = py_code context = {} exec(py_code, context) return context['var'][var_name].to_py()
""" @Author: 邓润庭 @Date: 2019/10/12 """ import js2py print(js2py.translate_js("console.log('Hello World!')")) # 将js翻译成python代码 js2py.translate_file('d02.js', 'd02.py')
import js2py import datetime now = datetime.datetime.now # the line below will # - build a 'compilation plan' by substituting strings and constants with placeholders # - then build the ast and emit the python code from that compilation plan # - then substitute back in the constants # This causes some regex overhead, but for js code with similar structure # subsequent translate_js calls are 20 times faster js2py.translate_js('name == "Robert" && age == 46', use_compilation_plan=True) # this lines below will re-use the compilation plan already laid out by the # statement above js2py.translate_js('name == "Guido" && age == 50', use_compilation_plan=True) js2py.translate_js('name == "Spam" && age == 25', use_compilation_plan=True) # now we'll show off the performance gain: start = now() for cnt in range(10000): js2py.translate_js('name == "Robert" && age == %i'%cnt, use_compilation_plan=False) print(('duration without compilation plan %i'%(now() - start).seconds)) start = now() for cnt in range(10000): js2py.translate_js('name == "Robert" && age == %i'%cnt, use_compilation_plan=True) print(('duration with compilation plan %i'%(now() - start).seconds)) # you can see how a compilation plan works with the lines below: from js2py.translators.translator import get_compilation_plan expression = "Age==1 && Gender==2 && JobTitle=='Decision maker'"
import js2py print(js2py.translate_js("console.log('hello world')")) # 将js文件翻译成Python脚本 # js2py.translate_file('test.js', 'test.py') # 第一个参数为需翻译的js文件,第二个为翻译后的文件 import js2py # 在js代码中导入Python模块并使用 # 使用pyimport语法 js_code = """ pyimport requests console.log('导入成功'); var response = requests.get('http://www.baidu.com'); console.log(response.url); console.log(response.content); """ js2py.eval_js(js_code)