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

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.

Related

Why main() function is called at the end of the program in python?

Lets consider the following piece of code in Python:
def main():
abc()
def abc():
.
.
.
<statements....>
.
.
.
main()
#Why the above line of code is used in python???
Lets consider other programming languages like C, C++ or Java or may be an interpreted language like BASIC. In BASIC, the code goes like this:
if the name of the module is module1 then:
Module Module1
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
This is in vbnet.
No Main() is called.
The above code is just for illustration.
So why is main() called at the end of the program in Python?
TL;DR
Because the creator of Python decided that was the way to use the language.
Details
Very simply put, it's a similar convention in those compiled languages you mentioned, like Visual Basic, C or C++ (or also Java, C#, and many other), that a program is started by launching the Main() function (with some variation, like in a module that is defined as the startup when you compile it).
So, basically, when you compile, in the binary .exe. the compiler adds a call to this Main() function, even if you haven't written it in your code.
Whereas in a Python program, it's simply the file itself that is run, line by line. There is no convention that any function would be called. Python is not a compiled program, not much happens "behind the scenes" (actually, not entirely true, some global variables are set by the interpreter Python.exe).
So, in your Python program, if there wasn't a line main() at the end, you would just have defined 2 functions abc and main, but nothing would be actually called and your program would stop after the definition, nothing inside the two functions would be executed.
In the end, it's just that Python language has a different rule than those languages you mentioned. It's by design of the language.
Of course, it's not "rnadom", this design is more "natural" depending on the type - compiled or interpreted - of the language. For instance, you have a similar behavior in JavaScript, there is no "main()" function either, a JavaScript code is also executed starting from the top, line by line, with potential functions defined in the main code.
(Simplified explanation, some special case may apply).
Its because you have to define the function before calling it in Python. If you call it before the definition, it may give you an error. A VB program launches the Main() function automatically inside the startup module.
The general rule in Python is that a function should be defined before its usage, which does not necessarily mean it needs to be higher in the code.
lol()
def lol():
print("Hello")
Should not work, but if you try
def test():
lol()
def lol():
print("Hello")
test()
It works.

How to initialize JS variables through Selenium 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).

How to use Python Interactive Window in VS Code with functions

I am new to using the python interactive window and I like it but it seems to clear local variables in between runs, so if I run something like
def main():
dates = '2012152'
# %%
print(dates) # want to just run this
# %%
if __name__ == '__main__':
main()
# or even
main()
all at once it works fine but then if I just run the middle cell I get "dates not defined" error. It works outside of the function because apparently a global variable is saved:
dates = '2012152'
# %%
print(dates) # this works if this cell is run
# %%
Is there any way to get a similar behavior inside a function? If not it doesn't seem useful to me at all (maybe I have designed my code badly?).
Cells are a great way to experiment with flat code, but they are limited when working nested inside functions.
One way to work around this is to use a regular built-in python debugger and set a breakpoint within the function.
Here is a process I use for experimenting with code inside a function:
Set a breakpoint in the function, after the code you want to experiment with and start debugging.
Make any necessary changes to the code.
Select the lines that you've changed and that you want to run again. Make sure to include all the indentations as well.
Right-click and select Evaluate in Debug Console.
This will allow you to run the code one line at a time, see results, and make any necessary adjustments as you go along.
The process could be further improved by binding a keyboard shortcut to the this command.
Yes, print(dates) will not run as the dates variable isn't in scope, unless the function main is called and even then dates will be only in the local scope of the function, not in global scope.
So to print it outside the function, you need to first define it.

How do I run a function in a print statement? Where the function itself contains a print statement

I am trying to create a variable to be used in more than one place to print a line of script
I tried using this to print: print(helped), didn't work, it gave the error you see. I tried doing this: print helped(), gave a syntax error
def helped():
print('''Type
Type
Type''')
weirdness = input('''What function would you like to run?
Type "Help" for possible commands ''')
if weirdness.upper() == "HELP":
print (helped)
When I enter "helped" upon being prompted, I get:
What function would you like to run?
Type "Help" for possible commands helped
I think you need a bit of help
instead of getting the print statement
How do i resolve the issue such that this wont happen?
In Python when calling a function, you must use the parentheses. So since your function's name is helped, you should call it like this:
print( helped() )
You should do this regardless of whether your function has parameters.
On a side note, with Python 2.6, you could have also use the print function without parentheses like this:
print helped()
but this is not the case with Python 3.x
You simply need to execute the function. Currently, the helped() function is defined but not run in your code. Essentially, it's never used. Right now you use print (helped) and should be getting a error when instead, you should call the function
Change
print(helped)
to
print(helped())

Importing code from a file as a function in python

Essentially I have a script in one file which I would like to import and run as a function in another file. Here is the catch, the contents of the first file CANNOT be written as function definition it just needs to be a plain old script (I'm writing a simulator for my robotics kit so user experience is important). I have no idea how to go about this.
Adam
Anything can be written as a function.
If you additionally need the ability to call your script directly, you just use the __name__ == '__main__' trick:
def my_function():
... code goes here ...
if __name__ == '__main__':
my_function()
Now you can import my_function from the rest of your code, but still execute the file directly since the block at the end will call the function.
Assuming that the code in the file you need to import is a well bounded script - then you can read in as a text variable and use the "execfile" function to create a function from that script.
By well bounded I mean that you understand all the data it needs and you are able to provide all of it from your program.
An alternative would be to use the "system" call, or the subprocess module to call the script as if it was an external program (depending if you need the script output).
A final approach will be to use exec to create a function - see approach 3.
The approach you use determines what you need your other script to do ..
examples :
hello.py (your file you want to run, but can't change):
# Silly example to illustrate a script which does something.
fp = open("hello.txt", "a")
fp.write("Hello World !!!\n")
fp.close()
Three approaches to use hello.py without importing hello.py
import os
print "approach 1 - using system"
os.system("python hello.py")
print "approach 2 - using execfile"
execfile("hello.py", globals(), locals())
print "approach 3 - exec to create a function"
# read script into string and indent
with open("hello.py","r") as hfp:
hsrc = [" " + line for line in hfp]
# insert def line
hsrc.insert(0, "def func_hello():")
# execute our function definition
exec "\n".join( hsrc) in globals(), locals()
# you now have a function called func_hello, which you can call just like a normal function
func_hello()
func_hello()
print "My original script is still running"

Categories