where does the python start the code execution from? [duplicate] - python

This question already has answers here:
understanding the execution flow in python
(2 answers)
Closed 3 years ago.
I am trying to understand that when we execute a .py file, then from which part
of that code the python start the execution from?
E.g.when we execute a Java program, the "public static void main(String[] args)" is the location where the java start the code execution. So, when we talk about python, how does it work? I know there is a python main function
(__name__ = "__main__")
, I have gone through some article in and out of the Stackoverflow, they all say that it loads the python module, and then the python UDFs etc. So, as per my understanding, it is the location which is executed first thing. Please correct me, or guide me to some web links for my query.

If the Python code is in a method, no code will be executed unless you explicitly call the method (e.g. after checking __name__ == '__main__'). It is convention to call main method, but you can call any method as the starting point of execution.
If the Python code is not in a method, the code will be executed anytime you run or import the file.

Related

How to have a subprogramm in another programming language [duplicate]

This question already has answers here:
How do I run a Python script from C#?
(8 answers)
Run a python script from unity, to use its output (text file) in my game later
(4 answers)
Closed 1 year ago.
I want to make a Unity game that gives data to a subprogram written in Python and this subprogram gives back an answer, that is then processed in the C# game.
I don't really know how to approach this.
Can I run python code from C# somehow or do I let two separate programs running, that exchange data somehow?
Both programs also need access to the same database.
You can make a python server using flask or fastAPI and then access it from C#. I am not sure how to get that done with C#(I dont know C# :( ), but there must be some libraries to call servers. Also, you could save the database on the cloud such as mongoDB.

Which Python module ,libraries are available for OSX Automation? [duplicate]

This question already has answers here:
Which is the easiest way to simulate keyboard and mouse on Python?
(5 answers)
Closed 5 years ago.
I am searching for any module for OSX automation like opening any app via Python and controlling mouse, keyboard via Python etc. I tried with AppleScript but I was wondering if I can access mouse, keyboard and can automate any app on OSX using Python? I found pyauto, If there is any other good Python library, module for OSX automation please let me know.
I too am looking for a good python module to use 'applescript' within python. In fact this is how I got here. I was unable to find anything so I had to come up with my own solution.
What works well for me is to call osascript from within my python programme using the subprocess module.
More precisely, (see the code below for an example), if I want to add something to my calendar I generate the applescript that does it as string in my python programme and then pipe it into osascript.
This is not super elegant and probably also not super fast but it works well. So, I am currently writing a calendar module that has python functions for adding events, getting list of events .... and each generates the applescript as string and calls osascript.
It sounds terrible but works quite well and once you have a module for your favourite programme you don't need to worry anymore about applescript.
One needs a way to encode in the applescript the return data and then decode it in the python programme. As for me most data passed to and from the applescript are dictionary-like, this has not been an issue so far using the re module.
Here is an example to get the uid of the calendar "Birthdays".
The main problem with my method is that I need to write wrapper functions for everything I want to access in applescript. A tiresome process.
The main advantage I see is a) it works and I get where I want and b) it seems future proof. For, if apple at some point discards applescript in favour of javascript or whatever, then all my programmes will still work once I adapted the wrapper modules.
Anyway ...
Hope that helps.
By the way, if anyone knows of a better way let me know. Or if someone does not know of a better way but likes my approach and would be interested in helping writing wrapper modules, let me know as well.
Here is the example.
Best,
Stephan
import subprocess
def asrun(ascript):
"Run the AppleScript ascript and return the standard output and error."
return subprocess.run(['osascript'],
input=ascript,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8")
def get_uid_of_calendar(name):
script = '''\
tell application "Calendar"
return uid of calendar "'''+name+'''"
end tell
'''
cal_res = asrun(script)
return cal_res.stdout
get_uid_of_calendar("Birthdays")

Python REPL in Django [duplicate]

This question already has answers here:
How do I execute a string containing Python code in Python?
(14 answers)
Closed 7 years ago.
I want to execute python code in my browser. Now I enter code in text-field in template, took it to view, where doing following:
source = request.POST.get('source', '').replace('"', r'\"')
result = commands.getoutput('python -c "%s"' % source)
I used python's module command for this, but I think it's don't correct way.
Correct way is using code module, but I don't understand how to get result of execution code and organise REPL. Can you give a little tip how to do it, please?
UPD: I want to start interactive shell in my browser with some variables. User can write some functions to manipulate this vars in browser and see that comes out of it. I understand the danger of this, but now it is not relevant.
You need to take a look at eval and exec also it is potentially very dangerous from security point of view.

Python call function from another file each time the function is called [duplicate]

This question already has answers here:
python refresh/reload
(7 answers)
Closed 7 years ago.
I've read this post How to call a function from another file in Python to see how a function can be loaded from another file. I have production code that runs all day and I want to be able to change only one function in that code to test/change output. I don't want to restart the program each time I need to verify my changes were successful.
Is there a mechanism to load the function each time it's called instead of importing the function at the beginning of the program and using the same code throughout the life of that particular instance? I moved the import statement from the beginning of the program into a loop, and the same output is observed no matter how much I change the function in the accompanying file.
A similar analogy would be HTML and CSS styling. I can have separate files there and change the CSS to change the output of the HTML without actually touching the HTML.
There is indeed a way to make the changes made to an external module reflected in a program/python session without having to restart the program . We can use the reload() method (or importlib.reload() for Python 3.x, if anyone is interested) . Example -
...
import <module>
reload(<module>)
But please note, you would need to do this whenever you want to reload the module.
I would say it would not be a good design to have a python program run for a long time, if it keeps repeating itself in specific iterval . It would be a better design to have a cron job or external scheduler run the python program when needed. In case the complete python program is restarted, reloading the module would not be needed, since Python would always take load the module again for each run.
You can use the importlib.reload function instead if you're using Python 3. For Python 2, use just reload.
import MyModuleWithAFunction
import importlib
...
importlib.reload(MyModuleWithAFunction)
Read more here.

Embedded Python - Blocking operations in time module

I'm developing my own Python code interpreter using the Python C API, as described in the Python documentation. I've taken a look on the Python source code and I tried to follow the same steps that are carried out in the standard interpreter when executing a py file. These steps (sequence of C API function calls) are basically:
PyRun_AnyFileExFlags()
PyRun_SimpleFileExFlags()
PyRun_FileExFlags()
PyArena_New()
PyParser_ASTFromFile()
run_mod()
PyAST_Compile()
PyEval_EvalCode()
PyEval_EvalCodeEx()
PyThreadState_GET()
PyFrame_New()
PyEval_EvalFrameEx()
The only difference in my code is that I do manually the AST compilation, frame creation, etc. and then I call PyEval_EvalFrame.
With this, I am able to execute an arbitrary .py file with my program, as if it were the normal Python interpreter. My problem comes when the code that my program is executing makes use of the time module: all time module operations get blocked in the GIL! For example, if the Python code calls time.sleep(1), this call is blocked and never gets executed.
Obviously I am doing something wrong that blocks the GIL (and therefore blocks the time module) but I dont know how to correct it. The last statement in my code where I have control is in PyEval_EvalFrameEx, and from that point on, everything runs "as in regular Python interpreter", I think.
Anybody had a similar problem? What am I doing wrong, so that I block the time module?
Hope somebody can help me...
Thanks for your time. Best regards,
R.
You need to provide more detail.
How does your interpreter's behavior differ from the standard interpreter?
If you just want to run arbitrary source files, why are you not calling one of the higher level interfaces, like PyRun_SimpleFile? Did your code call Py_Initialize?

Categories

Resources