Given only source file, what files does it import?
<p>I'm building a dependency graph in python3 using the <code>ast</code> module. How do I know what file(s) will be imported if that import statement were to be executed?</p>

<p>As suggested in a comment: the other answers are valid, but one of the fundamental problems is that your examples only work for 'simple' scripts or files: A lot of more complex code will use things like dynamic imports: consider the following:</p>

<pre><code>path, task_name = "module.function".rsplit(".", 1);
module = importlib.import_module(path);
real_func = getattr(module, task_name); 
real_func();
</code></pre>

<p>The actual original string could be obfuscated, or pulled from a DB, or a file or...</p>

<p>There are alternatives to importlib, but this is on top of the exec type stuff you might see in @horia's good answer.</p>

python python-3.x python-import abstract-syntax-tree