Home > Blockchain >  Python import pandas not working when used within .bat file
Python import pandas not working when used within .bat file

Time:11-19

I had the following issue that was giving me a lot of troubles. I managed to solve it after 2 1/2 hours and to spare some poor soul the same waste of time I wanted to show how I resolved it.

Loading a python file inside a .bat file was usually working quite well. However, I encountered issues when I tried to import pandas. Code could look like this

import pandas as pd
print ("hello")

and the following result in the cmd prompt would be

ImportError: Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

My .bat file would look like

@echo off
"C:\Users\myUserName\Anaconda3\python.exe" "C:\path to .py file\MyPythonFile.py"
pause

CodePudding user response:

To solve this I tried a variety of things like playing around with paths within windows and a large variety of other things. After I opened python.exe within the Anaconda3 folder, I received

Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated.  Libraries may fail to load.  To activate this environment
please see https://conda.io/activation

I found myself unable to resolve this within the command prompt but I managed to finally understand the core problem. With Anaconda3 being unactivated, it would never import pandas as intented while other imports were working as intented.

The solution that ended up working was adding the path of the activate.bat file inside the Anaconda3 folder. So the final .bat file would look like

@echo off
call "C:\Users\myUserName\Anaconda3\Scripts\activate.bat"
"C:\Users\myUserName\Anaconda3\python.exe" "C:\path to my Python Script\MyPythonFile.py"
pause

In a ideal scenario, I would be able to keep it activated but calling it within the .bat file is a adequate enough solution for me and may be enough for you too.

  • Related