Search code examples
pythonpython-3.xfiledirectory

How do I run another file in python?


So I know how to write in a file or read a file but how do I RUN another file?

for example in a file I have this: a = 1 print(a)

How do I run this using another file?


Solution

  • file_path = "<path_to_your_python_file>"
    

    using subprocess standard lib

    import subprocess
    subprocess.call(["python3", file_path])
    

    or using os standard lib

    import os
    os.system(f"python3 {file_path}")
    

    or extract python code from the file and run it inside your script:

    with open(file_path, "r+", encoding="utf-8") as another_file:
      python_code = another_file.read()
    
    # running the code inside the file
    exec(python_code)
    

    exec is a function that runs python strings exactly how python interpreter runs python files.

    IN ADDITION

    if you want to see the output of the python file:

    import subprocess
    p = subprocess.Popen(
      ["python3", file_path], 
      stdout=subprocess.PIPE, 
      stderr=subprocess.PIPE
    )
    err, output = p.communicate()
    print(err)
    print(output)
    

    EXTRA

    for people who are using python2:

    execfile(file_path)
    

    exec_file documentation