0

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
  • 117
  • 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

1 Answers1

0

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
  • 117
  • 4
  • 10