How to initialize JS variables through Selenium python? - python

I am trying to execute a JS file through python, selenium but I think I miss something.
I tried to call the checking variable from safari console, but it shows the following error Can't find the checking variable.
I also tried to execute the following code line driver.execute_script('var checking=0;') but I got the same result when I tried to call the checking variable from Safari Console.
PYTHON CODE
driver.execute_script(open("/Users/Paul/Downloads/pythonProject/Social media/javascripts/Initializing Variables.js").read())
JS FILE
var checking;
function Checking(item) {
if (item) {
checking = true;
}
else {
checking = false;
}
}
Any ideas?

All variables will be available just in single execute_script command context. So it's not possible to define variable in one driver command and modify it or get by another, unless you put the data to document, localstorage or sessionstorage..
But you're able to declare and put something to the variable, just don't forget to return it's value in script.
If I execute this script with driver.execute_script
var a;
function setAValue(arg) {
a = arg;
}
setAValue(100);
return a;
you'll get 100 in the output result.
And if you want to run your file from script, the file should ends with the function invocation and the return statement.
Share function and variables between scripts
This is working example in groovy language (sorry no python env)
WebDriverManager.chromedriver().setup()
WebDriver driver = new ChromeDriver()
driver.get("https://stackoverflow.com/")
//define variable date and function GetTheDatesOfPosts
driver.executeScript('''
document.date = [];
document.GetTheDatesOfPosts = function (item) { document.date = [item];}
''')
//use them in new script
println (driver.executeScript('''
document.GetTheDatesOfPosts(7);
return document.date;
'''))
driver.quit()
it prints [7].

Here's a quick tutorial on local vs globally scoped variables.
If you run a command such as:
self.execute_script("var xyz = 'abc';")
and then go to the console to try to find xyz, it won't be there (xyz is not defined).
However, if you run:
self.execute_script("document.xyz = 'abc';")
then it will be in the browser console if you type document.xyz.
That's the short summary. If you just try to declare a local variable when run from execute_script, then it'll go out-of-scope after the script is run. However, if you attach a variable to a persistent one, that's one way of keeping the variable around (and still accessible).

Related

How to pass a variable to python script from c++

There are similar questions & answers to this kind of problem but I still can't find a satisfying answer to my specific problem:
I need to pass a variable (should be a global variable to this python script) to a python script from c++ code. I run this python script using following line in c++:
PyRun_SimpleString ( "exec(f.read())" );
and I want to pass this variable var="From c++" to the python environment so code in f script is able to access var variable.
I'm looking at PyDict_SetItem and PyDict_SetItemString, etc... but couldn't get it right. How can I do that?
Based on #mbostic 's comment, I did the following and it works:
add this line PyRun_SimpleString("var='From c++' ");
before this PyRun_SimpleString("exec(f.read())");.
This way f is able to access variable var.

Is there is way to display output of scala program in databricks?

I was trying to run the below scala code in the azure data bricks notebook.it was running fine but not printing anything.
it just shows defined object mainobj after running.
How can I display output?
object mainobj{
def main(args:Array[String])={
print("Hello")
}
}
Your code just defines the object mainobj with function main inside. It doesn't execute this function. To execute it, add a call to that function, for example, like this:
mainobj.main(Array())
But really, in the notebooks you don't need to wrap functions with objects - you can define them directly, like this:
def main2 = {
print("Hello")
}
and just call main2.

Passing the result of a python script to an ExtendScript `.jsx` file

So, I'm writing a python script that gets data from a google sheet and returns it back to an ExtendScript script that I'm writing for After Effects.
The relevant bits are :
getSpreadsheetData.py
def main():
values = getSpreadsheetRange("1M337m3YHCdCDcVyS4fITvAGJsw7rGQ2XGbZaKIdkJPc", "A1:Q41")
return processValues(values)
afterEffectsScript.jsx
var script_file = File("getSpreadsheetData.py");
var results = script_file.execute();
$.writeln(results);
alert("done!");
So, I have three questions :
How do I pass variables from the afterEffectsScript.jsx to the python script (for example the spreadsheet id and range)?
How do I get a return from the python script and return it back to the jsx file?
How do I make my afterEffectsScript to work async so that it can wait for the python script to get what it needs...
Thanks in advance for the advice!
-P
After Effects has the possibility to call system commands and get the result of stdout.
var cmd = "pwd";
var stdout = system.callSystem(cmd);
$.writeln(stdout);
Take a look into the AE Scripting Guide
You can pass variables via setting environment variables.
Small example how call external script with args from extendscript:
var script_file = File("getSpreadsheetData.py");
$.setenv("arg_1", "arg1_value");
$.setenv("arg_2", "arg2_value");
script_file.execute();
You python script should start with reading this varibles from environment: Access environment variables from Python

calling python script from node.js

I want to call python script from node.js
Here is my script : my.py
def printme( str ):
# print str;
return str;
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
My node script : testpy.js
var PythonShell = require('python-shell');
var pyshell = new PythonShell('my.py');
pyshell.on('message', function(message) {
console.log(message);
});
but getting error
events.js:85
throw er; // Unhandled 'error' event
Error: spawn python ENOENT
at exports._errnoException (util.js:746:11)
at Process.ChildProcess._handle.onexit (child_process.js:1046:32)
at child_process.js:1137:20
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
P.S I have install Python shell
Also if I want to execute individual function from node.js to python script. can I do that ?Help
You can simply write the 'my.py' file like this-
def printme(str):
return str;
print(printme("I'm first call to user defined function!"));
Check if the path given is correct and check for indentation errors.
Your print statement (my.py line 2) is commented out so nothing will be output and the message event will therefore never fire. Uncomment your print statement, the Node PythonShell object will redirect the stdout (which print writes to) and fire a message event with the output.
As for your error, it looks like the python script isn't being found in the current directory. See https://docs.python.org/2/library/errno.html for error codes and what they mean. Make sure your script is in the right directory or set your python shell to the correct directory using os.chdir.
I think that you need to set up the python script to take in standard input like this
import sys
for v in sys.argv[1:]:
print v
Also when setting up the code the way you have it you need to do a PyhtonShell.send('message'), but I would need to see more of your code because I don't see how you are sending data to the python shell through Node.js.
You can simply import Npm Pythonshell using let keyword instead of const Keyword.
let {PythonShell} = require('python-shell')
this works for me

Powershell - now to extract name of variable passed to script

I am writing powershell script to interface with an external software program our company is using
The script needs to take in value of the input parameter and do something.
But the problem is, this external software pushes many input parameters with the names
sender-email
sender-ip
sender-port
endpoint-user-name
endpoint-machine-name
I only need the value for sender-ip. But my problem is
I don't know in which order the external program is inputting the parameters to the script
Powershell naming convention does not allow for a hyphen, so it's not like I can just start using sender-ip without getting an error The term 'sender-ip' is not recognized as the name of a cmdlet, function, script file, or operable program.
Here is my script so far
param([string]$Sender_IP=$(**sender-ip**))
$eventList = #()
Get-EventLog "Security" -computername $Sender_IP `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
| Select-Object -First 2 `
| foreach-Object {
$row = "" | Select UserName, LoginTime
$row.UserName = $_.ReplacementStrings[5]
$row.LoginTime = $_.TimeGenerated
$eventList += $row
}
$UserId = $eventList[0].UserName
$UserID
See, when I manually invoke foo.psl *ip_address*, everything works well. But if I call the program without parameter, I get error.
How to write code such as
if name of input variable is **sender-ip**
do something
else if name of input variable is something different
ignore
I am not evaluating value of the input parameter, I want to capture the input parameter that is named sender-ip, and from there I will run the script and evaluate.
I hope I explained my question well.
In the past, people interfaced with this third party program using Python script, where you can simply write the following
attributeMap = parseInput(args)
dateSent = attributeMap["sender-ip"]
I strongly prefer to use powershell.
Thank you!
If I were you I would probably start with looking at actual input to your script when your program runs...
If it will however just do:
.\yourscript.ps1 -foo-bar something -something-else value -sender-ip yourdata
You can get the value of sender-ip very easily:
param (
${sender-ip}
)
"Sender IP = ${sender-ip}"
If that's not the case you will probably have to paste here what you get when you do simple $args in your script. Without seeing what is there it may be hard to suggest something similar to thing that python does...
EDIT
In case you receive data as name=value pairs, try this:
function foo {
$hash = ConvertFrom-StringData -StringData ($Args -Join "`n")
$hash.'sender-ip'
}
foo test-first=alfa sender-ip=beta
In my test I got expected (beta) result...

Categories