【问题标题】:Running a python file within a different directory在不同的目录中运行 python 文件
【发布时间】:2021-08-16 07:18:21
【问题描述】:

我如何从main.py 运行整个test.pymain.pytest.py 都分配在应用程序文件夹中。 test.py 文件位于 app 文件夹中。我怎么能做到这一点,我下面的代码不起作用?

目录:

application folder
├── appFolder
│   └──test.py
└── main.py

Main.py:

from .appFolder import test
from subprocess import call
call(["Python3","test.py"])

【问题讨论】:

    标签: python-3.x function import directory subprocess


    【解决方案1】:

    您无需导入任何内容,只需引用main.py 中的文件夹名称即可。为了使其更健壮,您可能应该使用相对文件,否则您可能会得到一些奇怪的结果,具体取决于调用 main.py 的位置。

    import os.path
    from subprocess import call
    
    d = os.path.dirname(os.path.realpath(__file__))  # application folder
    call(["python3", f"{d}/appFolder/test.py"])
    

    另请参阅:https://stackoverflow.com/a/9271479/1904146

    【讨论】:

      猜你喜欢
      • 2016-12-16
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2021-12-15
      • 2019-08-13
      • 2012-12-15
      相关资源
      最近更新 更多