Forum Archive

Run another Python script from current Python code

victordomingos

Is it possible in Pythonista3/Python3 to call and run an external script? I have to separate Python3 applications in Pythonista. I want to run the first one and have it calling the second one automatically at some point, without merging its functions. I have read somewhere about an execfile() function, but it seems to be missing from current documentation. Any idea?

bennr01

@victordomingos execfile is deprecated in python3. You could use the runpy-module for running another script.

cvp

I use

webbrowser.open('pythonista://folder/name.py?action=run
victordomingos

@bennr01 said:

@victordomingos execfile is deprecated in python3. You could use the runpy-module for running another script.

It seems that this kind of execution need some adaptation in the code. I have my main code inside a if __name__ == "main": clause. That seems to be stopping my second file to run properly. Do I neet to stop using if __name__ == "main":, or is there a better way to do it?

victordomingos

@cvp said:

I use
webbrowser.open('pythonista://folder/name.py?action=run

Very strangely, i seem to have the same issue reported above. But when I add a print() statement in the end of the second script, outside of the if __name__ == "main": clause, it runs the whole code, including what is inside that clause. Why does that happen?

victordomingos

Actually, after a retry, it seems that only the code outside the if __name__ == "main": clause. The rest of code does not output anything.

bennr01

@victordomingos when using runpy.run_path, runpy sets __name__ to <run_path>. You can pass run_name="__main__" to runpy.run_path to change this.
EDIT: Also, use if __name__ == "__main__" instead of if __name__ == "main".

victordomingos

@bennr01 said:

@victordomingos when using runpy.run_path, runpy sets name to . You can pass run_name="main" to runpy.run_path to change this.
EDIT: Also, use if name == "main" instead of if name == "main".

That's what I meant, "main" was a typo here. :-)

Thanks for thew help!