Python Forum

Full Version: Python call/running another python file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello World!

I have two files python, ex: file1.py and file2.py

Now I'm working in file2.py and I need to run all the python code from file1.py inside(when I'm running) the file1.py.

how I can make this possible?

I already saw some websites that i have to do:

import file1.py
in the beginning, but I don't know how to run.

And last question, I will have problems with same variables used in the files, or doesn't matter
import file1
Then you can use the classes and functions that are defined in file1
Example

file1.py
variable = 'variable'

def file1_function(text):
    print(f'output from file1: {text}')
file2.py
import file1

print(f'output from file2: {file1.variable}')
file1.file1_function('from file2')
output from running file2.py
Output:
output from file2: variable output from file1: from file2
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException



def init_driver():
	driver=webdriver.Firefox(executable_path="C:\\Users\\jpedr\\Desktop\\geckodriver-v0.26.0-win64\\geckodriver.exe")
	driver.wait=WebDriverWait(driver, 5)
	driver.get("www.")
	return driver


def get_data(b,driver):
	try:
		driver.refresh()
		import time 
		time.sleep(5)
		driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
		d1=driver.find_element_by_xpath("/html/body/div[2]/main/div/div/div[2]/div/div/div/div[3]/div[2]/section[1]")
		b=b+1
		print("casa",b)
		
	except NoSuchElementException as e:
		print("no more casa total=",b)
		get_data.b=b
	






driver=init_driver()


import time 
time.sleep(5)
driver.refresh()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
import time 
time.sleep(2)
i=0
try:
	e1=driver.find_element_by_xpath("/html/body/div[2]/main/div/div/div[2]/div/div/div/div[3]/div[2]/section[1]")
	i=i+1
	print("casa",i)
	e2=driver.find_element_by_xpath("/html/body/div[2]/main/div/div/div[2]/div/div/div/div[3]/div[2]/section[2]")
	i=i+1
	print("casa",i)
	
except NoSuchElementException as e:
	print("numero de casas é", i)


get_data(0,driver)

print (get_data.b) 

import principal
quit()
while True:
	try:
		if i==get_data.b or get_data.b<i:
			import time
			time.sleep(60)
			print("step 1")
			get_data(0,driver)
			print(get_data.b)
			print("repetition")
	except ValueError:
		print("changed")

if i!=get_data.b and get_data.b>i:
	print("runother py file")
	import principal
	print("finished")
	pass
I having a error

Error:
Traceback (most recent call last): File "C:\Users\jpedr\Documents\tes3.py", line 109, in <module> import principal ModuleNotFoundError: No module named 'principal'
in this case is line 62, I just remove some lines for be short
windows11

you code is not very clear from what you have pasted - i can not determine if that is all one .py file or you have multiples there and what modules hold what code. Python requires you to define any functions etc before you can reference and same with variables, it also by good practise would expect all your import / from statements to be at the top of the module, thus letting any reader of your code to understand what packages/modules are required and then being to apply to the following code.
If you re-post your code (assuming it is not all one module) it may be easier to acertain where you error is arising.

also be sure to post your code inside python tags to aid clarity
This is the two files that I have.
I need to run the principal file inside from test.

the principal file works perfectly.

And I cal the principal in the line 78 from test file.

the error appear is
import principal
ModuleNotFoundError: No module named 'principal'

Hope now is clear my situation

file name: test
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException



def init_driver():
	driver=webdriver.Firefox(executable_path="C:\\Users\\jpedr\\Desktop\\geckodriver-v0.26.0-win64\\geckodriver.exe")
	driver.wait=WebDriverWait(driver, 5)
	driver.get("https://www.")
	return driver


def get_data(b,driver):
	try:
		driver.refresh()
		import time 
		time.sleep(5)
		driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
		d1=driver.find_element_by_xpath("/html/body/div[2]/section[1]")
		b=b+1
		d2=driver.find_element_by_xpath("/html/body/div[2]/section[2]")
		b=b+1
        #etc....
	except NoSuchElementException as e:
		print("no more, total=",b)
	get_data.b=b
	






driver=init_driver()


import time 
time.sleep(5)
driver.refresh()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
import time 
time.sleep(20)
i=0
try:
	e1=driver.find_element_by_xpath("/html/body/div[2]/section[1]")
	i=i+1
	e2=driver.find_element_by_xpath("/html/body/div[2]/section[2]")
	i=i+1
	#etc...
except NoSuchElementException as e:
	print("total", i)


get_data(0,driver)
print ("i=",i)
print ("get_data.b=",get_data.b) 

while True:
	print ("get_data.b=",get_data.b)
	if i==get_data.b or get_data.b<i :
		try:
			import time
			time.sleep(5)
			print("replay funtion")
			get_data(0,driver)
			print("b", get_data.b)
		except ValueError:
			print("something happen")
			break
	if i!=get_data.b and get_data.b>i:
		break
	pass


if i!=get_data.b and get_data.b>i:
	print("run another python file")
	import principal
	print("principal finished")
	pass
file name: principal

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys


def init_driver():
	driver=webdriver.Firefox(executable_path="C:\\Users\\jpedr\\Desktop\\geckodriver-v0.26.0-win64\\geckodriver.exe")
	driver.implicitly_wait(5) # seconds
	driver.wait=WebDriverWait(driver, 15)
	driver.get("https://www.")
	
	return driver


def my_function(i,driver):
	while i<b:
		import time
		time.sleep(15)
		driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
		element=driver.wait.until(EC.presence_of_element_located((By.XPATH,f[i])))
		
		while True :
			try:
				if find_element_by_xpath(f[i]) is True:
					element1=driver.find_element_by_xpath(f[i])
					driver.find_element_by_xpath(f[i]).click()
			except ValueError:
				print("no more")

			pass
		
		try:
			element = driver.find_element_by_xpath(f[i])
			driver.execute_script("arguments[0].click();", element)
		except NoSuchElementException as e:
			print("no")
		try: 
	     
			myDynamicElement = driver.find_element_by_xpath("/html/body/div[2]/div/form/input")                                                  
			driver.find_element_by_xpath("/html/body/div[2]/main/input").click()           
		
		except NoSuchElementException as e:
			driver.wait.until(EC.presence_of_element_located((By.XPATH,"/html/body/div/form/input")))
		import time
		time.sleep(2)
		driver.back()
		i=i+1

a=0
i=0
b=0
bypass=0





driver=init_driver()


    
f1="/html/body/section[1]"
f2="/html/body/section[2]"




f=[f1,f2]

driver.wait.until(EC.presence_of_element_located((By.XPATH,"/html/body/section[1]")))
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
try:

    c1=driver.find_element_by_xpath("/html/body/section[1]")
    a=a+1
   
except NoSuchElementException as e:
	print("no")
	
import time
time.sleep(10)
if a>0:
	driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
	driver.find_element_by_xpath("/html/body/div[3]").click()
	element=driver.wait.until(EC.presence_of_element_located((By.XPATH,"/html/body/section[1]")))
	driver.find_element_by_xpath("/html/body").click()
	try: 
		
		myDynamicElement = driver.find_element_by_xpath("/html/body/div[2]")                                                  
	
		driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
		import time
		time.sleep(2)

		driver.find_element_by_xpath("/html/body").click()           
	
		try:
			myDynamicElement = driver.find_element_by_xpath("/html/body/div[2]
			driver.find_element_by_xpath("/html/body/div[2]").click()
			driver.wait.until(EC.presence_of_element_located((By.NAME,"username")))
			driver.find_element_by_name("username")
			import time 
			time.sleep(2)
			driver.find_element_by_name("username").send_keys("")
			driver.wait.until(EC.presence_of_element_located((By.NAME,"password")))
			driver.find_element_by_name("password")
			import time 
			time.sleep(2)
			driver.find_element_by_name("password").send_keys("")
		import time
		time.sleep(2)
		driver.wait.until(EC.presence_of_element_located((By.XPATH,"/html/body/div[2]")))
		driver.find_element_by_xpath("/html/body")
		driver.find_element_by_xpath("/html/body").click()           
		
	
		import time 
		time.sleep(2)




try:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    d1=driver.find_element_by_xpath("/html/body/div[2]/main/")
    b=b+1
    d2=driver.find_element_by_xpath("/html/body/div[2]")
    b=b+1
    
except NoSuchElementException as e:
	print("no more")





if b>0:
	my_function(0,driver) 

  
What are the absolute paths to your python files? When you 'import principal' it must be in the same directory as your 'test.py' file.

Also, in your principal file line 102 is missing double quotation mark and a parenthesis - is that in your real file?
Another thing, you use 'time.sleep()' so many times, and every time you use it, you 'import time'. Why don't you just put 'import time' at the top of your scripts so you don't need to keep importing it?
Thank you, the problem was the files was in different folders.
And the principal I remove parts from X_path because was to big and maybe was more difficult to read, and I delete that, by mistake in the line you say. But the principal file runs well.