简体   繁体   English

如何从主 python 文件正确运行单独的 python 脚本?

[英]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.我试图让我的 python 脚本更加模块化——当所有内容都在一个冗长的 .py 文件中时它可以正常工作,但我想使用主 python 文件调用其他文件来简化流程并使升级更容易。

I'm struggling with package imports.我正在为包导入而苦苦挣扎。 One package I'm using is os , which I import in the main file:我正在使用的一个包是os ,我在主文件中导入它:

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:我还在名为 code_module_1.py 的 python 文件的顶部导入它:

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 .当我这样做时,我收到一条错误消息,指出the name 'os' is not defined ,我认为这意味着该包没有被导入到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?我应该在哪里导入包,以及如何确保被调用的其他 python 文件具有它们需要运行的包?

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.您可以在其中执行先前导入的函数function_called_from_main

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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