简体   繁体   中英

How do I properly run a separate python script from main python file?

I am trying to make my python script more modular -- it works properly when everything is in just one lengthy .py file, but I want to use the main python file to call other files to streamline the flow and make upgrades easier.

I'm struggling with package imports. One package I'm using is os , which I import in the main file:

import os
import pandas as pd
import numpy as np
from code_module_1 import *

if __name__ == '__main__':
    code_module_1()

I also import it at the top of the python file that is called, code_module_1.py:

import os
import glob
import pandas as pd
import numpy as np

def function_called_from_main():
    for root, dirs, files in os.walk('...file_path'):
        etc.

When I do this, I receive an error saying the name 'os' is not defined , which I've taken to mean that the package isn't being imported in code_module_1 .

I've attempted to fix this by placing the lines of code that import packages inside of the function that I'm calling from the main script, but I still run into the same error. Where should I be importing packages, and how do I make sure that other python files that are called have the packages that they need to run?

With the following line

from code_module_1 import *

you import everything defined in the module. So basically, all function definitions are available.

Next, you can't execute a module. You can only execute a function or a statement. Thus, the following line

if __name__ == '__main__':
    code_module_1()

should be something like this:

if __name__ == '__main__':
    function_called_from_main()

where you execute the function function_called_from_main that was previously imported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM