0

I have utils.py and there are two functions: runrealcmd, mol_with_atom_index

If I try to import the two function with the following code:

from utils import mol_with_atom_index, runrealcmd

It fails to import runrealcmd. The error message is like below:

ImportError: cannot import name 'runrealcmd' from 'utils'

However, if I try to import only the mol_with_atom_index with the following code:

from utils import mol_with_atom_index

It successes. The function of mol_with_atom_index can be imported in Jupyter notebook.

However, the function of runrealcmd cannot be imported in Jupyter notebook although both of the two functions are in the same utils.py file.

ImportError: cannot import name 'runrealcmd' from 'utils'

utils.py

from subprocess import Popen, PIPE, STDOUT
from IPython.core.magic import register_line_magic

@register_line_magic
def runrealcmd(command):
    # Display instantly: https://stackoverflow.com/questions/52545512/realtime-output-from-a-shell-command-in-jupyter-notebook
    process = Popen(command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True)
    for line in iter(process.stdout.readline, b''):
        print(line.rstrip().decode('utf-8'))
    process.stdout.close()
    process.wait()


def mol_with_atom_index(mol):
    for atom in mol.GetAtoms():
        atom.SetAtomMapNum(atom.GetIdx())
    return mol
Hyunseung Kim
  • 493
  • 1
  • 6
  • 17
  • 1
    Something is weird because the code you posted combined with `from utils import mol_with_atom_index, runrealcmd` works fine. Are you clearing your kernel first after changing your `utils.py` code? You can launch a session via mybinder by [clicking here](https://mybinder.org/v2/gh/fomightez/pythonista_skewedf/HEAD) and try it out on a separate, **temporary** system in your browser. – Wayne Jan 28 '22 at 04:51
  • Thank you. It's so weird. Actually, there were 4 functions in utils.py, but only one function (mol_with_atom_index) was imported... I think that I need to ty to clear my kernel first. – Hyunseung Kim Jan 28 '22 at 06:57
  • Once you use `import `, the kernel will import and record it has already imported that package. If you then put `import ` for the same package again in another cell it will 'run' that code; however, behind the scenes it won't have imported again because it noted it already did. Besides restarting the kernel, you can [reload](https://stackoverflow.com/a/5399339/8508004) modules. – Wayne Jan 28 '22 at 14:22
  • Not Clearing the kernel before importing the same-named function from the other path seems the cause. After clearing the kernel, it has been solved. Thank you – Hyunseung Kim Feb 06 '22 at 08:18

1 Answers1

0

(Jupyter notebook) If you want to import the same-named function (previously imported with the same name) from the other path, you should restart the kernel first.

Hyunseung Kim
  • 493
  • 1
  • 6
  • 17