动态模块导入在python中不起作用-为什么不呢?

时间:2019-10-28 10:51:07

标签: python python-import

我正在尝试将python脚本foo.py动态导入到另一个可执行脚本中,该脚本位于深度嵌套的文件夹中。我正在使用

import os
sys.path.insert(0, '../../../../.') 
from foo import Bar

这有效,我可以愉快地使用Bar

我想使脚本动态确定文件夹深度,例如

import os
root_path = os.path.relpath(os.popen("git rev-parse --show-toplevel").read()).replace("../reponame", ".")
print(root_path) # prints '../../../../.'
sys.path.insert(0, root_path)
from foo import Bar

但是这不起作用,脚本抱怨说它在运行时找不到Bar。

这是为什么?

1 个答案:

答案 0 :(得分:2)

如果您进行调试,则会看到<?php namespace App\Traits; use Illuminate\Support\Facades\Log; trait PropertyBaseTrait { private $org_id; private $token; private $is_set; public function __construct() { $this->org_id = setting('propertybase_org'); $this->token = setting('propertybase_token'); } public function base_url($method) { return 'https://pb-integrations-api-staging.herokuapp.com/api/v1/'.$method.'/'.$this->org_id.''; } public function post_lead($data) { $lead_data = array( 'first_name' => '', 'last_name' => '', 'email' => '', 'phone1' => '', 'phone2' => '', 'phone3' => '', 'address' => '', 'city' => '', 'state' => '', 'zip_code' => '', 'country_name' => '', 'landing_page' => '', 'search_term' => '', 'referral_source' => '' ); $object_type = 'lead'; $action_type = 'create'; dd($this->token); $endpoint = $this->base_url('messages'); $this->post_data( $endpoint, $object_type, $action_type, json_encode($data)); } 实际上是root_path。删除'../../../../.\n'

\n