How to execute another Python file from current script? - python

So I have a login script called login.py. When user log in, script will create a user session and execute main.py and close login.py. How to do this?

I'm a little confused by what you need help with but try this:
from fileName import function_you_want
Ideally you don't want a script to run on an import. It can cause some unexpected things to happen. At the bottom of main.py I would use this:
if __name__ == "__main__":
call_your_function()
This way you can do tests by running the script directly or calling a specific method from another py file without running the script.

What you can do is import that file main.py like import main. If you want everything from that file, from main import *
Then, after the user logins, destroy your main window using <Tk>.destroy() and then call your function.

Related

How to reload the main file in Python console?

I'm doing updates to other modules imported in my main file, and I can reload them on the fly in the console and get the new behaviour immediately via
import importlib
importlib.reload(module_name)
How can I do this for the main file?
I tried __name__ but did not work.
PS: I have gigantic datasets and I hate running again the main file after tiny changes, takes forever.
You should put your code in the main file into a main function and add this to the end:
if __name__ == "__main__":
main()
This will let you reload the module while also letting you run it normally. However, after you reload, you have to call module.main().

How to execute one python script in a different directory with another script?

I am trying to execute one python script (file2.py) through the other (file1.py).
The first file is located in test/file1.py and the second file in test/test1/file2.py.
As an example file2.py has the following code:
file = open("textfile.txt","w")
file.write("Hello world")
file.close()
so I am trying to create a .txt file from file1.py.
To do so, I have tried several solutions such as:
import Test1.file2
or
import os
os.system('Test1/file2.py')
or
from subprocess import call
call('Test1/file2.py', shell='True')
in file1.py but none of them seem to work. The first solution works well if I want to import a function but it does not work when I want to create a text file.
Does anyone know what I am doing wrong and how to fix it?
To run the other file, you have some options:
The best one is to treat the file as a module, import it, and call it's methods, so you would have to encapsulate the .txt creating inside a method
#on file1.py
def createTxt():
#your txt creation goes here
and call createTxt from file2.py importing file1.py, which will run the method and create the txt file
#on file2.py
import file1
createTxt()
You can also use execfile('file2.py') to execute it and run it as a script or make a system call with os.system('python file2.py') importing os to also run as a script
The first one is safer and a better code in general, avoid using the other two when possible

Importing functions between two Python scripts simultaneously

I am trying to run a chat bot of sorts that is capable of creating new commands whilst the program is running. To do this I am keeping all the commands in a second python script and using the main script to edit the commands.py file whilst the chat bot is still running.
The issue...
I am able to have both scripts access each other using import main and then main.functionName() to call the function. However, when I try to call a function in commands.py from main.py, then use the function called to call another function back in main.py I get an error saying
AttributeError: module 'main' has no attribute 'exampleFunction'
For example the following code;
TESTING.py
import TESTING2
def runme(inp):
print(inp)
startOver()
print("begin")
TESTING2.startOver()
TESTING2.py
import TESTING
def startOver():
userInput = input("Enter text at your own risk... ")
TESTING.runme(userInput)
Produces the following;
begin
Traceback (most recent call last):
File "C:\Users\harry\Desktop\TESTING.py", line 1, in <module>
import TESTING2
File "C:\Users\harry\Desktop\TESTING2.py", line 1, in <module>
import TESTING
File "C:\Users\harry\Desktop\TESTING.py", line 8, in <module>
TESTING2.startOver()
AttributeError: module 'TESTING2' has no attribute 'startOver'
The desired outcome would be a continuous loop of entering an input and then the text being printed as if one seamless script.
Is this possible? If so how do I do it - or is there a better way to achieve the same goal?
Many thanks.
So, I'll have a go at giving you something that might solve your problem. Essentially what you are doing is constructing a circular dependency: commands.py is written by main.py, main.py depends on commands.py for its functions. There is almost certainly a way to solve your problem without introducing such a circular dependency, but I would need to know more in order to suggest something.
If you are sure you want to do it like this, you could use importlib.reload, which tells python to reload a module that you've already imported. In other words, if you've added a new function to commands.py since calling the original import, calling reload will now make this function available.
As a small example, try setting up commands.py and main.py scripts as follows:
#commands.py
def func1():
print(1)
and:
#main.py
import commands
commands.func1()
input("hit enter once you've edited commands.py")
from importlib import reload
commands = reload(commands)
commands.func2()
run main.py and when you get to the input part, open up commands.py and change it to look like this:
#commands.py
def func1():
print(1)
def func2():
print(2)
Now hit "enter" in the running main.py script. You should see the result of func2printed to the terminal.
Note however also that reload doesn't necessarily act the way you would expect and could cause some strange and explainable things to happen. For more info, see this post: https://stackoverflow.com/a/438845/141789

Importing variables from another Python script

Is it possible to import a Python script into a main script and then just use the variables? I don't want the other script to execute inside of the main script, just attach one of the variables...
If you can edit the script being imported, there's a solution:
Put all the executed code into a block starting with
if __name__ == '__main__':
In this way, the code in the if block above will be executed only if the script is run directly. i.e. when you run python script.py.
You can import only the variable like this:
from script import var
If you want to import the variable without going through the whole script, then as per Python's design it's not possible. import will always go through the whole script being imported, and will avoid whatever that's inside __name__ == '__main__'.
You have an option to read the script file and find the variables, then do it yourself by parsing and executing it, but IMO that's unnecessary job to do since you have import.
You can see the answers under Python: import module without executing script

how to execute nested python files

I have 3 python files.(first.py, second.py, third.py) I'm executing 2nd python file from the 1st python file. 2nd python file uses the 'import' statement to make use of 3rd python file. This is what I'm doing.
This is my code.
first.py
import os
file_path = "folder\second.py"
os.system(file_path)
second.py
import third
...
(rest of the code)
third.py (which contains ReportLab code for generating PDF )
....
canvas.drawImage('xyz.jpg',0.2*inch, 7.65*inch, width=w*scale, height=h*scale)
....
when I'm executing this code, it gives error
IOError: Cannot open resource "xyz.jpg"
But when i execute second.py file directly by writing python second.py , everything works fine..!!
Even i tried this code,
file_path = "folder\second.py"
execfile(file_path)
But it gives this error,
ImportError: No module named third
But as i stated everything works fine if i directly execute the second.py file. !!
why this is happening? Is there any better idea for executing such a kind of nested python files?
Any idea or suggestions would be greatly appreciated.
I used this three files just to give the basic idea of my structure. You can consider this flow of execution as a single process. There are too many processes like this and each file contains thousandth lines of codes. That's why i can't change the whole code to be modularize which can be used by import statement. :-(
So the question is how to make a single python file which will take care of executing all the other processes. (If we are executing each process individually, everything works fine )
This should be easy if you do it the right way. There's a couple steps that you can follow to set it up.
Step 1: Set your files up to be run or imported
#!/usr/bin/env python
def main():
do_stuff()
if __name__ == '__main__':
The __name__ special variable will contain __main__ when invoked as a script, and the module name if imported. You can use that to provide a file that can be used either way.
Step 2: Make your subdirectory a package
If you add an empty file called __init__.py to folder, it becomes a package that you can import.
Step 3: Import and run your scripts
from folder import first, second, third
first.main()
second.main()
third.main()
The way you are doing thing is invalid.
You should: create a main application, and import 1,2,3.
In 1,2,3: You should define the things as your functions. Then call them from the main application.
IMHO: I don't need that you have much code to put into separate files, you just also put them into one file with function definitions and call them properly.
I second S.Lott: You really should rethink your design.
But just to provide an answer to your specific problem:
From what I can guess so far, you have second.py and third.py in folder, along with xyz.jpg. To make this work, you will have to change your working directory first. Try it in this way in first.py:
import os
....
os.chdir('folder')
execfile('second.py')
Try reading about the os module.
Future readers:
Pradyumna's answer from here solved Moin Ahmed's second issue for me:
import sys, change "sys.path" by appending the path during run
time,then import the module that will help
[i.e. sys.path.append(execfile's directory)]

Categories