I am trying to execute some JavaScript code through Python.
def home():
code = """
var regexp = new RegExp(/playerCaptionsTracklistRenderer.*?(youtube.com\/api\/timedtext.*?)"/);
var url = regexp.exec(document.body.innerHTML)[1];
open("caption.py?url=" + encodeURIComponent(url));
"""
code = quote(code, safe='~()*!.\'')
return """YouTube Transcriber"""
As I understand, variables from Python must be passing to JavaScript automatically, but I get the following exception in last line in JavaScript:
Uncaught ReferenceError: code is not defined
You aren't telling python to put the contents of code into your returned string. You could do it like this:
return """YouTube Transcriber"""
You can't just put a variable name in a string and expect its contents to be automatically put into the string. It's not clear why you would expect that to happen. It's something you explicitly have to do, via either string formatting, or concatenation.
Inside your return statement, inside the JS function, there is literally the word "code", which is undefined. You probably wanted to enter the value of the variable code in which case you need to break the string apart, and add the code variable in between like this:
return """YouTube Transcriber"""
Related
PyPDF2 update page form field values function working fine with hardcoded strings but nothing shows if using variable text.
I have tried using string variables like this
writer.update_page_form_field_values(
#writer.pages[0], {"Piece Weight": variableString} doesn't work
writer.pages[0], {"Piece Weight": "hardcoded string"}#works
)
as well as like this
writer.update_page_form_field_values(
#writer.pages[0], {"Piece Weight": f"{variableString}"} doesn't work
writer.pages[0], {"Piece Weight": "hardcoded string"}#works
)
I am expecting the final output file to show the text I store into a string variable within the field named "piece weight" but what actually happens is absolutely no data is displayed on in the field when a variable is applied to it.
UPDATE-
found that my issue was not that it refuses to show variable data, rather it was a matter of, my variable data not being updated after it is initialized. I am creating it at one point
variablestring = ""
and then later in the code i am attempting to change it within a function
def onStart():
variablestring = variableEntry.get()
This is an issue of scope as the variablestring within the function and outside the function are seen as separate memory spaces.
there in lies an issue however, I can not pass this function parameters as it needs to be automatically called by a
tkinter.Button(form, text="start", command=onStart)
Final answer to my issue was to use the global tag to call the variable outside of the function into it.
variable = "te"
def onStart():
global variable
variable = variableEntry.get()
when reading about globals for python i misunderstood it as a declarative global and not a call global
I'm storing code snippets inside the Postgres DB. When I need the code, I find it inside the DB and use exec() function. The code snippet is a body of extract function.
Unfortunately it returns SyntaxError: 'return' outside function
Method
def extract(self,response):
exec(self.custom_code)
Code snippet (repr(code_snippet))
u"return response.xpath('/text()')"
I suppose that it should behave like this:
def extract(self,response):
return response.xpath('/text()')
What I should do?
This is just one line snippet and I need to execute multiline snippets.
EDIT:
I'm using Django with PostgreSQL and I realised that it strips spaces at the beginning of the line - indentation. I don't know if it has to do something with the problem.
EDIT2:
Tried eval instead of exec. Now it raises:
File "/home/milano/PycharmProjects/Stilio_project/stilio/engine/models.py", line 107, in extract
eval(self.custom_code)
File "<string>", line 1
return response.xpath('/text()')
^
SyntaxError: invalid syntax
Per the exec docs:
Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec statement.
So exec is explicitly off-limits. And that wording is global, not specific to exec; on checking, while eval using code compile-ed in 'single' mode has the same error; you can't dynamically insert return statements like this.
If you absolutely must allow executing arbitrary code, I strongly recommend limiting it to expressions, not statements, and implicitly returning the result of said expressions. So instead of storing u"return response.xpath('/text()')", you'd store u"response.xpath('/text()')", and your code that performs dynamic invocation would change to:
def extract(self,response):
return eval(self.custom_code)
I want to get an entire Python function and save it as string (for instance, Javascript can simply do functionString = functionVar.toString().
Example:
#I defined a function with a body:
def someFunction(hey):
return hey + hey + hey
I want to convert this function to string and get exactly the same text as I typed above (without the comment, of course)
Then I want to do the inverse operation: from the string, convert it to a function and and store it in a variable to be called.
Using exec you can almost get what you're asking. Encoding the function as a string is the easy part.
"""Encode the function as a string"""
import inspect
funcString = inspect.getsource(someFunction)
Retrieving the function from the string is a touch more work. The following approach will have issues with globals or other variables outside the scope of the function you're trying to recover, but if the source completely specifies it then the following idea should work.
d = {}
exec(funcString, d)
f = next(d[k] for k in d if k != '__builtins__')
After running, the code defined by the source used to generate f in the first place will be bound to the variable f.
I want to determine whether the input string is a valid function name or not.
Is there any way to substitute the value of the variable before being passed to isfunction call ?
#!/usr/bin/python
def testFunc():
print "Hello world!";
return;
myString = "testFunc";
isfunction(testFunc); // This returns **True**
isfunction(myString); // This returns **False**
One way of doing that is using eval, which interprets string as code:
try:
eval(myString)
except NameError:
# not a function
Assuming you want to check to see if there exists a loaded function with You could try this:
try:
if hasattr(myString, '__call__'):
func = myString
elif myString in dir(__builtins__):
func = eval(myString)
else:
func = globals()[myString]
except KeyError:
#this is the fail condition
# you can use func()
The first if is actually unnecessary if you will always guarantee that myString is actually a string and not a function object, I just added it to be safe.
In any case, if you actually plan on executing these functions, I'd tread carefully. Executing arbitrary functions can be risky business.
EDIT:
I added another line to be a bit more sure we don't actually execute code unless we want to. Also changed it so that it is a bit neater
So basically, let's say you define a function and then write something in () brackets after then function. If I write function(gay), it ends up as 'error name not defined' Python2.73
def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
print type(aStr)
return
def lenRecur2(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
s = str(aStr)
print type(s)
return
So when I type lenRecur(gay) or lenRecur2(gay), it ends up as an error whatever I do. So is there a way to avoid it? Without using "" quote marks.
No - unless your input is already a variable that holds a string (or another object).
However, you could use a try-except block (but it won't actually do anything if there's an error).
try:
lenRecur(foo)
lenRecur2(foo)
except NameError:
pass
The error occurs before the function even gets called. Python tries to evaluate the arguments before calling the function. So, Python encounters the bare name gay and wonders, "What the hell is that?"
When it fails to find its value in the local, enclosing, global or builtin scopes, it raises a NameError.
There is no way around this. You must clearly specify what you mean. If gay is a string, you must use quotes.