Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import statement is not working when running python script from the command line

I need to run a python script from the command line (OS = Debian wheezy, python -version 3.5).

I used PyCharm (community edition) to write the script and it is working from inside the IDE.

I used sys.path.append command to add the directory containing the package I want, then followed it with this import line:

from package_name,file_name import ClassName

The Error message in the command line: ImportError: No module named 'package_name'

enter image description here

like image 928
user2804070 Avatar asked Feb 07 '23 14:02

user2804070


2 Answers

if you are running any xxx.py file and you face the import error though same script if run by any IDE works fine,its path issue.

What worked fine for me is: Go to file which shows import module issue and before importing module(for which issue is seen),add the path of module to sys using append.

for example ,I was running the script file from conf path and my script was importing module situated in \scripts\Setup\ so appended the path of module like below.

import sys
import os
conf_path = os.getcwd()
sys.path.append(conf_path)
sys.path.append(conf_path + '\scripts\Setup') 

then use import statement of module for which issue was thrown.

like image 156
Avinash Kumar Jha Avatar answered Feb 09 '23 03:02

Avinash Kumar Jha


I found the answer for my question above, and the problem was much easier than I thought.

Addressing the Problem

  • having many python packages in different directories
  • your script needs some/all packages, that are not in the standard lib-directory for your python installation (e.g.:prefix/lib/pythonVersion).

Solution

Short term solution

As long you are using an IDE (e.g. PyCharm), it is sufficient within the code to add:

import sys sys.path.append("path/to/package")

As soon as you have to run your script from the command line, you will get an ImportError as mentioned in the Question above.

Better solution

Add the directories of your packages and of your python installation to your shell-profile(e.g.: .bashrc) using the command:

export PYTHONPATH=prefix/lib/pythonVersion:/path/to/packages

To get more info about PYTHONPATH, check this link

In this case you will not need to append the path of your packages within your code :)

like image 36
user2804070 Avatar answered Feb 09 '23 03:02

user2804070