1

What is the proper way to import a script that contains a period, such as program_1.4.py, ideally using importlib?

(Now that the imp module is deprecated, this this answer no longer applies: How to reference python package when filename contains a period .)

JBT
  • 167
  • 2
  • 4
  • 10
  • Take note that the proper way is most certainly either to fix the module by renaming it, or to run it as an executable as it was meant to be. – MisterMiyagi Sep 21 '20 at 20:02
  • As one of the answers to the linked question says, this is not possible. – Seth Sep 21 '20 at 23:00
  • @Seth Of course it is possible: Python is Turing-complete. There may not be a very Dutch solution, but I am looking for the simplest, lowest-overhead answer I can get for this real-world use case where stand-alone programs (non-local, read-only, etc—so no renaming) are linked together as part of a larger application. – JBT Sep 22 '20 at 00:11
  • @JBT Even though importing these files is possible, in general, just because a language is Turing complete doesn't mean that it can do anything - it just means it can run any algorithm, but not that it can to import certain file types. Take, for example, a Turing machine: it is by definition Turing complete, but it can't import any files because that's not part of the semantics (and it was invented before computers...). – Oli Nov 25 '21 at 16:41
  • Does this answer your question? [How to reference python package when filename contains a period](https://stackoverflow.com/questions/1828127/how-to-reference-python-package-when-filename-contains-a-period) – Hongbo Miao Nov 29 '22 at 06:13

1 Answers1

1

After looking through the CPython quite a lot and coming back to some other solutions (especially Import arbitrary python source file. (Python 3.3+)), I realized that I needed to pass the full path to my module. Here is the cross-platform, call-location-independent solution:

"""

import os, sys # For running from Notepad++ shortcut, etc
import importlib.machinery

program_1_4 = importlib.machinery.SourceFileLoader('program_1.4', os.path.join(sys.path[0], 'program_1.4.py')).load_module()

print(program_1_4)
program_1_4.main()

"""

JBT
  • 167
  • 2
  • 4
  • 10
  • I posted a new solution using `importlib` and `pathlib` at https://stackoverflow.com/a/74609764/2000548 The reason using `pathlib` instead of `os` is at [here](https://towardsdatascience.com/dont-use-python-os-library-any-more-when-pathlib-can-do-141fefb6bdb5) – Hongbo Miao Nov 29 '22 at 06:22
  • @HongboMiao That also works (same principle), but I'd stick with `"""os"""` because it provides a lower-overhead approach. Avoid objects when strings suffice. More secure, too. – JBT Dec 14 '22 at 00:35