importError using a virtualenv from cmd on Windows - python

trying to run a flask dev server on localhost:5000 using a virtualenv on Windows 7
In my command line in the project directory, i activated the virtualenv with the command "env\scripts\activate". It seemed to work, as my next line was preceded with an (env) tag. When I attempted to run the app file (bank_app), however, I got an import error.
Here's the console log
C:\Users\TJ\Documents\Python Projects\TestingPython> env\scripts\activate
(env) C:\Users\TJ\Documents\Python Projects\TestingPython> bank_app
Traceback (most recent call last):
File "C:\Users\TJ\Documents\Python Projects\TestingPython\bank_app.py", line 1, in <module>
from flask import Flask
ImportError: No module named flask
and here's a gist of the bank_app file (just in case it's relevant)
I'm used to running the code directly from PyCharm, which handles the virtualenv for me. it works fine running directly from PyCharm

This is probably related to how Windows maps extensions to executables.
You started the script with bank_app, which is really not the name of your script (your script has a .py extension I assume?). Windows must be doing a search in your directory, and then starting the script with the interpreter that is registered for the .py extension of the script, which is the globally installed interpreter, not the interpreter that is currently in the PATH.
I'm pretty sure if you run the command as python bank_app.py everything will work just fine.

Related

Imported module cannot be found when Python script is run via a bat file

I know there has been similar problems, but unfortunately most of them are related to errors with pyperclip itself instead of the batch file, which i suspect is where the problem stems from.
Below is an MRE of my Python script:
#! python3 -> Do I have to use my version(3.8)?
# pw.py - An insecure password locker program.
import sys, pyperclip
#do something with the module
And my batch file pw.bat:
#py.exe C:\Users\KEVIN\PycharmProjects\atbs_exercise\pw.py %*
#pause
I am running python 3.8 on windows 10. I imported the pyperclip module in my python script pw.py and ran the file via pw.bat, and this in turn gives me this error:
Traceback (most recent call last):
File "C:\Users\KEVIN\PycharmProjects\atbs_exercise\pw.py", line 7, in <module>
import sys, pyperclip
ModuleNotFoundError: No module named 'pyperclip'
Press any key to continue . . .
Which shouldn't happen as I have installed pyperclip on the project using pip, and the script itself runs just fine in pycharm. What am I missing?
EDIT: I forgot to mention that I am using pycharm. So the thing is that pycharm had also installed python.exe in the project folder. And as the module pyperclip is only installed to that folder, the python.exe used in the bat must point to the one in the project folder.
i don't know why are you using py.exe. when running commands from a batch file or cmd .you should use python.exe.obviously you would need to add python to add for doing so.instead of adding py.exe to path,add python in system variable Path which is somewhere present in C:\Users\[username]\AppData\Local\Programs\Python\(your path might be diffrernt).you can add python in Path by following this post
after adding python to path just use the following batch-file:
#echo off
python path-to-your-py-file\filename.py

Pyinstaller create an executable with external libraries

I am trying to create an executable file (exe) for a Python script that I written in PyCharm.
When I run the script from the PyCharm is working fine but when I try to run it as an individual .py or try to run the exe I am getting an error.
The issue I believe is with the "from infi.devicemanager import DeviceManager" library.
from infi.devicemanager import DeviceManager # Used for the retrievement of Device manager information
dm = DeviceManager()
dm.root.rescan()
devs = dm.all_devices # Get all the devices to a list called devs
for d in devs:
print (d.description)
I get following error:
PS C:\Python> python.exe .\tests.py
Traceback (most recent call last):
File ".\tests.py", line 1, in <module>
import infi.devicemanager # Used for the retrievement of Device manager information
ModuleNotFoundError: No module named 'infi'
PS C:\Python> pyinstaller -F .\tests.py
PS C:\Python\dist> .\tests.exe
Traceback (most recent call last):
File "tests.py", line 1, in <module>
ModuleNotFoundError: No module named 'infi'
[15072] Failed to execute script tests
Is there a way to include this library to the exe file so anyone without python can run this script?
I am open to suggestions.
Thank you in advance!
=== UPDATE ===
Full script can be found here
https://github.com/elessargr/k9-serial
My answer assumes that the interpreter that has infi.devicemanager is C:\Python\venv\Scripts\python.exe as stated by OP in the comments
So there is virtual environment named venv. You need to activate the virtual environment and install PyInstaller in it.
C:\Python>venv\Scripts\activate
(venv)C:\Python>
Note (venv) in front of your shell - that means virtual environment venv is activated
Now install PyInstaller
(venv)C:\Python>pip install pyinstaller
-- here it will install pyinstaller --
now you can test that both pyinstaller and infi.devicemanager are installed in venv
(venv)C:\Python>pip list
it should list both packages among some others. now
(venv)C:\Python>pyinstaller -F C:\Python\tests.py --hidden-import=infi.devicemanager
--here it will create the exe --
if I was right it should work now
EDIT: It looks like infi is using __import__(pkg_resources), so the command should be
(venv)C:\Python>pyinstaller -F C:\Python\tests.py --hidden-import=infi.devicemanager --hiden-import=pkg_resources

Python script within a Pipenv as a windows service with NSSM

Using How do you run a Python script as a service in Windows? I can get a python script to run as a service. Tested it with the following code I made:
import os
from time import sleep
from random import *
# import flask <-- This line breaks it only when run from NSSM
count = 0
while True:
num = randint(1, 10000)
count+=1
os.mkdir("C:\\temp\\" + str(count) + '_' + str(num))
sleep(2)
I tested the executable and arguments to put into NSSM by first running the following:
cd C:\pipenvfolder\foo
C:\Users\Username\AppData\Local\Programs\Python\Python36\Scripts\pipenv.exe
run python main.py
And it starts the script successfully, even if it has imports to packages installed in the pipenv (e.g. flask). I then created a NSSM service with:
nssm.exe install ServiceName "C:\Users\Username\AppData\Local\Programs\Python\Python36\Scripts\pipenv.exe"
"run python main.py"
nssm set ServiceName AppDirectory
"C:\pipenvfolder\foo"
And every 2 seconds it creates a directory in c:\temp. All is good. However now I wish to import one of the installed Pipenv packages, i.e. the flask package installed within the pipenv. So I added "import flask" to the test script above.
I then set up NSSM to have an error log and checked why it was failing to start, and it is failing to import the flask module:
Traceback (most recent call last):
File "main.py", line 7, in <module>
import flask
ModuleNotFoundError: No module named 'flask'
The nssm service must be starting in the correct app directory or else it would not find main.py. Calling it from the correct directory is what specifies the pipenv. Hence I cannot figure out why the pipenv is not being used to run the script in the same way as when run via the command line.
Create a batch file which calls your virtual environment.
Get the virtualenv path:
pipenv --venv
service.bat
call path/to/.virtualenv/Scripts/activate.bat
call python main.py
Install the service with nssm which calls this batch file.
I doubt this is going to get any answers, but if someone else has the same issue.
I got around the issueby making an exe using pyinstaller. It is fairly quick and easy to do. Then I passed the .exe into NSSM as the executable to be run.

Pycharm doesn't copy root folder to PYTHONPATH

I'm using Pycharm community edition 2017.3 in Windows 10.
I'm running Python 2.7 with venv.
Till today all was good, but all of a sudden, PyCharm stopped adding the root folder to PYTHON path, and things stopped working (unless I add it manually to sys.path). I haven't change anything in the PyCharm configuration (at least not explicitly...). I tried closing and reopening PyCharm, reboot, clear the cache, cleaning Python compiled files, setting the root folder as 'sources root', but none seems to work.
The same code exactly is deployed on another computer and it's working.
This is the bad line:
from TM2_VAL_LAB import test_base, robot_handler
And this is the error:
Traceback (most recent call last):
File "C:/Users/baruchl/Documents/_GIT/TM2_VAL_LAB/TM2_VAL_LAB/test_vr_translation_ff.py", line 17, in <module>
from TM2_VAL_LAB import test_base, robot_handler
ImportError: No module named TM2_VAL_LAB
When I run the following during the python execution:
print os.getenv('PYTHONPATH')
I get:
None
When I run the same code in the remote computer (where everything running smoothly), I get:
C:\GIT\TM2_VAL_LAB
which is the root folder of the python script I'm running.
This is the run configuration I'm using:
This is how my project looks like:
Any ideas?
After few back and forth with PyCharm rep, the solution is to close PyCharm, rename/delete the .idea folder and re-open PyCharm.
That's it.
After this, when when running the same file as before,
print os.getenv('PYTHONPATH')
results in:
C:\Users\baruchl\Documents\_GIT\TM2_VAL_LAB
and
print sys.path
results in:
['C:\\Users\\baruchl\\Documents\\_GIT\\TM2_VAL_LAB\\TM2_VAL_LAB', 'C:\\Users\\baruchl\\Documents\\_GIT\\TM2_VAL_LAB', ...]

naoqi 2.5.5.5 and PyCharm CE 2017.1

I have an annoying problem with PyCharm CE and naoqi. Following the installation instructions in Aldebaran Guide, I have configured my environment to work with this one.
I have installed the version of python (python 2.7.13) suggested by Aldebaran, I have written the .bash_profile using:
# Setting PATH for Python 2.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH
#NaoQI 2.5.5
export PYTHONPATH=${PYTHONPATH}:/Users/francesco/Documents/PyLibs/pynaoqi-python2.7-2.5.5.5-mac64/lib/python2.7/site-packages
export DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:/Users/francesco/Documents/PyLibs/pynaoqi-python2.7-2.5.5.5-mac64/lib
after that, I launch my code in python from Terminal (making sure that the right version of python is called when I type
$ python my_code.py
and all is working (I tried also with virtualenv and all works fine if I launch all from terminal).
So far so good but then comes the poison arrow. I use PyCharm CE like IDE, I have created a new project that use the same environment that works fine in terminal and the magic happens..
The first issue is:
/Users/francesco/Documents/PyEnv/pynaoqi255_python2713/bin/python /Users/francesco/PycharmProjects/PepperRobot/PepperRobot.py
Traceback (most recent call last):
File "/Users/francesco/PycharmProjects/PepperRobot/PepperRobot.py", line 5, in
import qi
ImportError: No module named qi
(Ok seriuosly this is the same environment that in terminal works)
I try to bypass the problem, adding the content of naoqi sdk in the virtualenv's site-package. Ok, the problem is bypassed.. But there is another problem:
/Users/francesco/Documents/PyEnv/pynaoqi255_python2713/bin/python /Users/francesco/PycharmProjects/PepperRobot/PepperRobot.py
Traceback (most recent call last):
File "/Users/francesco/PycharmProjects/PepperRobot/PepperRobot.py", line 5, in
import qi
File "/Users/francesco/Documents/PyEnv/pynaoqi255_python2713/lib/python2.7/site-packages/qi/init.py", line 88, in
from _qi import Application as _Application
ImportError: dlopen(/Users/francesco/Documents/PyEnv/pynaoqi255_python2713/lib/python2.7/site-packages/_qi.so, 2): Library not loaded: #loader_path/libqipython.dylib
Referenced from: /Users/francesco/Documents/PyEnv/pynaoqi255_python2713/lib/python2.7/site-packages/_qi.so
Reason: image not found
Process finished with exit code 1
I did not understand why...
I have also include in
Preferences -> console -> Python Console -> Environment Variables
the same variables included in .bash_profile but to no avail.
How can I solve this tedious problem ?
I have solved my problem editing run/debug configuration and putting here the environment variable DYLD_LIBRARY_PATH. All works fine.

Categories

Resources