在运行命令时,哪些路径会添加到sys.path
中,哪些因素会影响它?
我的Python版本是3.6.4,我也在3.7版上尝试过。
目录结构为
.
├── __init__.py
└── src
├── a.py
└── b.py
代码是
# a.py
class A: pass
# b.py
from sys
print(sys.path)
from src.a import A
a = A()
print(a)
我尝试在具有相同Python版本的两台计算机上运行python3 src/b.py
。其中一个没有报告错误,而另一个错误发生了。
在正确的运行结果中,sys.path
中有两个目录,一个是当前目录,另一个是src
目录;
正确的输出是:
['/home/work/test/testimport/src', '/home/work/test/testimport',...]
<src.a.A object at 0x7f8b71535ac8>
错误的结果是:
['/home/work/test/testimport/src', ...]
Traceback (most recent call last):
File "src/b.py", line 3, in <module>
from src.a import A
ModuleNotFoundError: No module named 'src'
sys.path
仅包含src
目录。
当我运行python3 src / b.py时,哪个路径将附加到sys.path?
答案 0 :(得分:0)
using System;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Application.Repositories.History;
using Application.Repositories.I4Pro;
using Domain.Process.Enum;
namespace Application.Process.ProcessIntegrationUseCase.GenericClass
{
public class StartProcessHandler<T> : HandlerManager<T> where T: class
{
private readonly ILogger _iLogger;
private readonly IHistoryReadOnlyRepository _historyReadOnlyRepository;
private readonly II4ProReadOnlyRepository _i4ProReadOnlyRepository;
public StartProcessHandler(ILogger iLogger,
IHistoryReadOnlyRepository historyReadOnlyRepository,
II4ProReadOnlyRepository i4ProReadOnlyRepository)
{
_iLogger = iLogger;
_historyReadOnlyRepository = historyReadOnlyRepository;
_i4ProReadOnlyRepository = i4ProReadOnlyRepository;
}
public override void ProcessRequest(T history)
{
try
{
TypeIntegration typeIntegration = (TypeIntegration)history.GetType().GetProperty("TypeIntegration").GetValue(history);
_iLogger.LogInformation("Buscando execuções MetaIntegra");
var item = _historyReadOnlyRepository.GetLastHistory(typeIntegration);
_iLogger.LogInformation("Buscando execuções I4Pro");
var i4Process = _i4ProReadOnlyRepository.ListLastExecutions();
_iLogger.LogInformation("Executing Habitacional Integration_" + DateTime.Now.ToString());
if ((item != null && i4Process[0].Id_Processo_Log != item.LastIdI4Pro) || item == null)
{
history.GetType().GetProperty("LastIdI4Pro").SetValue(history,
item.LastIdI4Pro);
history.GetType().GetProperty("IdProcessoLog").SetValue(history,
i4Process[0].Id_Processo_Log);
if (base.sucessor != null)
sucessor.ProcessRequest(history);
}
}
catch (Exception ex)
{
_iLogger.LogError(ex.Message);
}
}
}
}
确实不是一个模块(不包含src
),并且它是否在您的路径中也没有关系。此外,__init__.py
仍然“看到”它所在的目录(b.py
),所以
src
无论您在何处执行from a import A
中的B
都可以工作。请注意,即使您确实创建了
python3 /path/to/src/b.py
如果您没有将目录`src/__init__.py`
添加到路径中,则您的b.py
将失败(或者 PYTHONPATH ,这是将python模块添加到路径中的推荐方法)