Import module error when running os.system virtualenv OpenCV - python

I'm trying to build a simple Python GUI around OpenCV so I can run facial recognition commands easily. I'm using a Raspberry Pi thus Raspbian to do this
It's a case of clicking a button and an os.system command executes allowing various functions to run.
The issue is with trying to run these functions whilst in the Virtual Python Environment. I need to be inside the virtualenv to gain access to the required modules however I understand every time a os.system command is ran, a new shell is created therefore taking me out the virtual environment.
I've looked into running my functions in one os.system however I still get the import module error.
Something that i assumed would take a few mins to build is taking me days.
Any help on this would be amazing.
Thank you.
Here is my current code:
from tkinter import *
import os
from tkinter import messagebox
# creating tkinter window
root = Tk()
root.geometry('500x500')
root.title("Student Attendnace System")
def stillImage():
os.system("/home/pi/.virtualenvs/cv/bin/activate & python recognize_faces_image.py ---encodings encodings.pickle --detection-method hog --image examples/example_01.jpg")
btn3 = Button(root, text = 'Detect Faces From Image', command = stillImage)
btn3.grid(column=1, row=2)
mainloop()
The idea is to enter the virtual environment and execute another python script with added facial detection arguments.
NOTE: running this in the terminal works fine.

I would use the python from the virtualenv directly:
os.system("/home/pi/.virtualenvs/cv/bin/python recognize_faces_image.py ---encodings encodings.pickle --detection-method hog --image examples/example_01.jpg")
To elaborate a script run using a python executable from a virtualenv will look for libraries relative to the python executable, i.e. inside the virtual environment.

Related

why I can't use tkinter module with batch file

Batch code:
TITLE %~nx0
python "c:\users\aaa\desktop\coding\python\first project with tkinter\buttomtest.py"
pause
and python code is:
from tkinter import *
window = Label(text="gg")
print("tt")
and this is what I get:
It shows the cmd prompt window but it doesn't show the window of tkinter
Tkinter is a python module meant ONLY for python.
Now I see what you tried to do but learning python may be the way there is an OS module import OS which could allow you to run command prompt commands. os.system("command here") will allow you to run commands from the system DOS.
Hope this helps and enjoy the community!
You may also run a start command
start File.py
Exit
way to fix that: window.mainloop()
and there is no need for import OS

How do you fix tkinter in python3.8 on wsl?

I was trying to learn GUI based python therefore i was using the Tkinter library. My OS is windows but I have installed Ubuntu wsl as my default terminal, and use wsl vscode as my default text-editor.
I was just creating a basic window using this sample code to check whether it works or not:
from Tkinter import *
def onclick():
pass
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
Turns out it does not work with python3.8.
Terminal error message
I looked up multiple resources and forums and could not find any proper solutions. Here are couple of links i have referred to:
https://realpython.com/python-gui-tkinter/ https://tkdocs.com/tutorial/install.html https://askubuntu.com/questions/1224230/how-to-install-tkinter-for-python-3-8 .
A work around I discovered was that installed anaconda which uses python3.7 and used the windows terminal instead (using pycharm not vscode). And it looks like it is functioning properly.
GUI with python3.7
The thing is.. I like wsl and vscode far better than windows command line, and I wanted to revert back to it. Is there any solution? I really do not want to fool around with the path too much because I had a bad experience previously (But i am willing to do it again if its going to fix my problem). Thanks for hearing me out.
The problem isn't Python, but WSL. You can't run anything graphical easily inside WSL. (Microsoft is planning to add that feature, but it isn't ready yet. There are third-party solutions, but they're not that easy to set up.)
The easiest solution is to use a Windows install of Python 3.8 to run your tkinter app. You can still invoke that from inside your Ubuntu WSL, same as any Windows executable.
WSL now supports graphical interfaces. In order to use it you need to install or update WSL more info. Then run your app as usual and your program window should open.

The following code is running through python IDE but not from CMD or by direct execution

import webbrowser
import pyautogui
import time
webbrowser.open("https://meet.google.com/huq-etkk-pwv",new=0,autoraise=True)
#auto_input
time.sleep(10)
pyautogui.hotkey('ctrl','d')
pyautogui.hotkey('ctrl','e')
time.sleep(2)
#custom coordinates are adviced
#coordinates work on standard chrome window with 1920*1080 screen size 16:9 ratio
pyautogui.click(972,428)
When i run this via CMD i get an error in the module pyautogui with Tk() name not defined and when i try to execute this directly it just opens a window of CMD and then stops and does nothing but works perfectly when i run it via the Python IDE.
Your code works fine for me on my Kubuntu (18.04.)
Which IDE do you use? Is it possible, that it by default runs a different version of python than your CMD (e.g. 3.7 in the IDE and 2.7 in the CMD)?
P.S.
would have posted it in a comment but lack the reputation

How to run python script on atom?

I'm new to using atom and was wondering how to run a python script on it. I have code written at the moment which works perfectly fine in normal python shell, using tkinter, however when I run it through the command line, it says:
import tkinter as tk
ImportError: No module named tkinter
How do I fix this? In my environment variables I have already added python.exe, the file directory to the actual script I'm running and to the python download itself. How do I fix this?
The best way is to load the Jupyter plugin. It's called Hydrogen. Then under the packages menu, you can select Hydrogen/Run all and it will run your python code. there is a keyboard shortcut for doing this which speeds up the process. You can easily check your code as you write it by using the hydrogen option to run a line and go to next line.
As for your Tkinter problem have you loaded Tkinter? You can do this using pip install Tkinter. After that try running your code again.
In python 2.7 and below, the modules's name is Tkinter, while in 3.0 and above, it is tkinter.
Atom (whatever this is) seems to use a 2.7 or below version of python interpreter.

Script works in IDLE, but .py-file doesn't work

I have a tkinter script, which runs just fine in IDLE. However, when I double click the .py-file from Windows Explorer, the console window flashes half a second and then it exits.
I was able to screenprint the console window. It says:
...etc.etc...
NameError: global name 'simpledialog' is not defined
simpledialog is a module in tkinter which I use in my script. As I do from tkinter import *, there is no need to explicitly write tkinter.simpledialog.
It works in IDLE, why not as .py?
IDLE uses Tkinter as its graphical environment. It is possible that your code is relying on a side effect of an import by IDLE itself. This is especially true if you use IDLE without a subprocess.
The simpledialog module does not import when using from tkinter import *.
Try adding this to your code:
import tkinter.simpledialog as simpledialog
Have you updated your PATH environment variable so that your Python executable is found? You can find more information on how to do here - Using Python on Windows
But you basically need to make sure that the folder containing python.exe (e.g. C:\Python32) is displayed when you type the following command from a prompt:
echo %PATH%
I had exactly the same problem with one of my scripts utilizing Tkinter.
Adding call to mainloop() fixed the issue.
See this tutorial for an example: [http://sebsauvage.net/python/gui/#import1
In my case, in the init function I have
def __init__(self,Width=400, Height=400):
# Create GUI window ------------------------------
win = Tk()
...
in the end of init I added:
win.mainloop()
Now it works by just running the file.
Hope this helps
Similar trouble for me just now, in my first week with python. But I dimly remembered a similar problem with a simple early test script and thought the trouble then was # comments.
So I tried that with my Tkinter infused .py script. It ran fine in IDLE as you say, then only flashed when clicked in windows. But there were a couple # commented lines at the top of file.
I took them all out and it now runs no sweat directly in windows. Have a look .. for #.
Sorry, can't seem to delete this post. Now the files work #comments included. Don't know what's up with that. ..
I found that changing the executable py file to a file.pyw fixed the problem. This tells python to execute it using the pythonw.exe which runs the script without the terminal/console in the background.
Not sure why this works, perhaps some screwed up environment variables from a previous python installation.
Changing the file's extension to pyw instead of py might solve the problem

Categories