简体   繁体   中英

How do I import a module using the command line?

I just started learning python and I'm having issues importing a module using the command line. So, I created a module and saved it as - Man_Data_PyDeck.py - and it here is the contained code in the module:

def fib_func(n):
    total = 0
    f1, f2 = 1, 2
    while f1 < n:
        if f1 % 2 ==0:
            total = total +f1
        f1, f2 = f2, f1 + f2
    return(total)

if __name__ == "__main__":
    limit = input("What is your chosen Max Fibonacci Number: ")
    print(fib_func(int(limit)))

I can easily execute this module using the command line as follows:

python Man_Data_PyDeck.py

When I try import the module using the command line I receive an Import Error. The code I'm trying to import it with is as follows:

import Man_Data_PyDeck

The error I receive is:

>>> import Man_Data_PyDeck
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'Man_Data_PyDeck'

Am I having path issues? What is causing this?

It is likely that your current working directory does not contain Man_Data_PyDeck.py file. Just make sure you are inside same folder where you *.py file locates.

Alternatively, you can add the folder where Man_Data_PyDeck.py is to the PYTHONPATH environmental variable, which would allow you to import Man_Data_PyDeck regardless of the working directory. You do this by something like the following in the terminal (CMD).

export PYTHONPATH="$PYTHONPATH:THE_FOLDER_WITH_PYTHON_FILES"

check the following When Working with modules:

  • The module you are trying to import is in python PATH variable. This Variable consist of path strings where python will search for when you try to import any package or module/scripts

to see which directories are search simply.

import os
print(os.environ['PATH'])

this will show all the paths (will work on Command line Python that you are trying) then simply add your full directory path to this variable the try importing the desized module

to add your directory path do the following:

os.environ['PATH'] += ':your/full/directory/path'

if you want to add the your path in the PATH without using python script use what Yang Yushi. :)

then import your module.
hope this helps <3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM