0

I am currently attempting to run another .py file via the following script. However, it will not run the other file.

import time
 
def talking():
   import talk

list1 = ["Whats the time", "WHATS THE TIME?", "WHATS THE TIME" "whats the time", "whats the time?", "Whats the time?"]
input("Whats your name?: ")
while True:

 ask = input("How can i help?: ")

 if ask in list1:
     talking()
 time.sleep(1)

 if ask == "hi":
     print("Hi?")
     time.sleep(1)

The file called talk currently simply contains the following:

import time

time.sleep(4)
print("Hello World")
time.sleep(20)

I have done this before but since then i have completely forgotten.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    Please provide a [mre] including input, expected output, actual output, and minimal code, like to start, `time.sleep()` doesn't seem relevant to the problem, and the input from `input("Whats your name?: ")` is unused. – wjandrea Dec 12 '21 at 20:15
  • 1
    With all the fluff removed, I'm not able to reproduce the issue. `tmp.py` = `import talk` and `talk.py` = `print("Hello World")` -> running `tmp.py` prints `Hello World`. – wjandrea Dec 12 '21 at 20:21

2 Answers2

3

As written in this other question you can execute a python executed.py script from another python executor.py script using exec(open("executed.py").read()) in executor.py.

In your case your talking() function becomes:

def talking():
    exec(open("talk.py").read())

This isn't the best way anyway. If you want to use your talk.py file as a library, you should define functions inside talk.py file, then importing them in the file where you want to execute them. Code below is an example.

talk.py

def talking():
    print("I'm talking")

caller_script.py

import talk

talk.talking()  # this will print "I'm talking"
wjandrea
  • 28,235
  • 9
  • 60
  • 81
-1

From your question which is interesting (even if written in an unclear way in some places, but it is understood), I read import talk in the main py file function, so I assume you want to import the secondary external file and use as a library.

To call an external file in the function of a main file, you have to call the name of the file and then of the function that you will have to create to be called. So it will be something like this:

In the main file main.py, you have to write like this:

#from file_name import function_name
from talk import example

def talking():
      talk_function = talk.example()
    return talk_function

If you want to import it from inside a folder, you have to write from Folder_name.talk import example

In the secondary file talk.py (the one you want to recall) you have to write:

def example():
    time.sleep(4)
    print("Hello World")
    time.sleep(20)

You can also run the whole file directly as @Marte Valerio Falcone said in his nice answer

Erling Olsen
  • 1
  • 4
  • 15