(os.path.dirname(__file__)) not working in FreeBSD - python

I want to set the path to the images dir..in my Django project...it is working fine but when i run the script on FreeBSD it is not working...
import os
imagesDirPath = (os.path.dirname(__file__)) + "/couponRestApiApp/stores/images/"
print imagesDirPath
output: /home/vaibhav/TRAC/coupon-rest-api/couponRestApi/couponRestApiApp/stores/images/
Above is working on my system but when tried it on freeBSD i get:
/couponRestApiApp/stores/images/
but it should be
/home/vaibhav/coupon-rest-api/couponRestApi/couponRestApiApp/stores/images/
Can someone tell me what is wrong...

Related

running a python exe without a command line and getting the hwid

So ive been trying to get the hwid of a device with a app im making however i cant seem to get the hwid when compiled without a command line.
import subprocess
import PySimpleGUI as sg
import os
a = subprocess.run("wmic csproduct get uuid",capture_output=True,text=True)
x = str(a.stdout).rstrip()
x = x.splitlines()
print(x[2])
sg.popup(x[2])
#wmic csproduct get uuid
The code works perfectly in vscode (also im on python 3.9 if that matters).

Unable to run program using Pycharm Debugger, but normal Run works fine when using opencv - [Errno 2] No such file or directory:

I have checked a lot of similar posts where users were having issues with the Pycharm debugger not working, but running it using the run button working fine, but none of them applied to an issue with opencv.
Here is my simple script:
import numpy as np
import cv2
image = cv2.imread('../FGVC/data/balloon/1548266469.88633.png')
image_2 = cv2.imread('../FGVC/data/balloon_mask/1.jpg')
cv2.imshow('img', image)
cv2.imshow('img2', image_2)
yo = np.bitwise_and(image, image_2)
ye = np.bitwise_or(image, image_2)
cv2.imshow('combined', yo)
cv2.imshow('combinedd', ye)
cv2.waitKey(0)
I get the following exception whenever I import cv2 through the python debugger.
[Errno 2] No such file or directory: '/home/user/anaconda3/envs/py36/lib/python3.6/site-packages/cv2/config-3.6.py'
I am using an anaconda virtual environment running Python 3.6. I did check that the cv2 directory and indeed there is no config-3.6.py file, but there was a config-3.py file, so I duplicated that and called it config-3.6.py, but then I started running into the following issue:
(<class 'KeyError'>, KeyError(b'LD_LIBRARY_PATH',), <traceback object at 0x7fe97dd32ac8>)
This is the content of my config-3.6.py file.
PYTHON_EXTENSIONS_PATHS = [
LOADER_DIR
] + PYTHON_EXTENSIONS_PATHS
ci_and_not_headless = False
try:
from .version import ci_build, headless
ci_and_not_headless = ci_build and not headless
except:
pass
# the Qt plugin is included currently only in the pre-built wheels
if sys.platform.startswith("linux") and ci_and_not_headless:
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "qt", "plugins"
)
# Qt will throw warning on Linux if fonts are not found
if sys.platform.startswith("linux") and ci_and_not_headless:
os.environ["QT_QPA_FONTDIR"] = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "qt", "fonts"
)
Edit: what is also strange is that after the exception being raised the rest of the open-cv script works as expected the same way it works with the run button.
I figured out that the issue was that I had made it so the Pycharm debugger would break "On Raise" of an exception for a different project and the settings carried over to this project.
I just unchecked the "On Raise" option and the problem was solved.

why my server terminal doesnt show error?

I am connected to my VPS (Ubuntu) via SSH.
I use Django, where I process 1000's of images via Django-imagekit ( PIL ). but for some reason, it is not generating an error it just stops/terminates there. it shows all other print commands and everything.
yes, I tried 'try and except' but it doesn't work, it just terminates at 'try' only.
CODE:
from imagekit import ImageSpec
from imagekit.processors import ResizeToFit
class Thumbnail(ImageSpec):
processors = [ResizeToFit(1200)]
format = 'WEBP'
options = {'quality': 90}
Main_image = open('path/to/image.jpg','rb')
Preview_gen = Thumbnail(source=Main_image)
Preview = Preview_gen.generate()
Error while executing the last line
( but works fine on my local machine )
Specs:
Ubuntu Linux 18.04.2
Python==3.6.9
Django==3.0.7
Pillow==8.2.0
psycopg2==2.8.6
psycopg2-binary==2.8.6
django-imagekit==4.0.2
anyone any idea?
error causing image Wallpaper, .jpg, 9600 x 5598
this is the problem for very few images

Running xlwings on a server

Solved the problem by making sure that python27.dll and win32api into the PYTHON_WIN directory. The two files with an arrow were missing in the server folder (P:/)
I am using udf module of xlwings and setting xlwings.bas configuration into a server. (I have my personal disk C:/ however other users need to run this macro and the file must be stored in P:/)
I have python, xlwings and other modules installed in P:/, but I get some strange error about importing os lib. Does any one have ever passed through this ?
Thanks in advance.
I got this from python:
"Python process exited before it was possible to create the interface object.
Command: P:\Python 27\python.exe -B -c ""import sys, os;sys.path.extend(os.path.normcase(os.path.expandvars(r'P:\Risco\Python Scripts')).split(';'));import xlwings.server; xlwings.server.serve('{2bb649ad-487e-48d5-ab31-24adaeefca59}')""
Working Dir: "
Xlwings.bas is set like this:
PYTHON_WIN = "P:\Python 27\python.exe"
PYTHON_MAC = ""
PYTHON_FROZEN = ThisWorkbook.Path & "\build\exe.win32-2.7"
PYTHONPATH = "P:\Risco\Python Scripts"
UDF_MODULES = "FetchPL"
UDF_DEBUG_SERVER = False
LOG_FILE = ""
SHOW_LOG = True
OPTIMIZED_CONNECTION = False

Python - How do you run a .py file?

I've looked all around Google and its archives. There are several good articles, but none seem to help me out. So I thought I'd come here for a more specific answer.
The Objective: I want to run this code on a website to get all the picture files at once. It'll save a lot of pointing and clicking.
I've got Python 2.3.5 on a Windows 7 x64 machine. It's installed in C:\Python23.
How do I get this script to "go", so to speak?
=====================================
WOW. 35k views. Seeing as how this is top result on Google, here's a useful link I found over the years:
http://learnpythonthehardway.org/book/ex1.html
For setup, see exercise 0.
=====================================
FYI: I've got zero experience with Python. Any advice would be appreciated.
As requested, here's the code I'm using:
"""
dumpimages.py
Downloads all the images on the supplied URL, and saves them to the
specified output file ("/test/" by default)
Usage:
python dumpimages.py http://example.com/ [output]
"""
from BeautifulSoup import BeautifulSoup as bs
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
import os
import sys
def main(url, out_folder="C:\asdf\"):
"""Downloads all the images at 'url' to /test/"""
soup = bs(urlopen(url))
parsed = list(urlparse.urlparse(url))
for image in soup.findAll("img"):
print "Image: %(src)s" % image
filename = image["src"].split("/")[-1]
parsed[2] = image["src"]
outpath = os.path.join(out_folder, filename)
if image["src"].lower().startswith("http"):
urlretrieve(image["src"], outpath)
else:
urlretrieve(urlparse.urlunparse(parsed), outpath)
def _usage():
print "usage: python dumpimages.py http://example.com [outpath]"
if __name__ == "__main__":
url = sys.argv[-1]
out_folder = "/test/"
if not url.lower().startswith("http"):
out_folder = sys.argv[-1]
url = sys.argv[-2]
if not url.lower().startswith("http"):
_usage()
sys.exit(-1)
main(url, out_folder)
On windows platform, you have 2 choices:
In a command line terminal, type
c:\python23\python xxxx.py
Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.
For your posted code, the error is at this line:
def main(url, out_folder="C:\asdf\"):
It should be:
def main(url, out_folder="C:\\asdf\\"):
Usually you can double click the .py file in Windows explorer to run it. If this doesn't work, you can create a batch file in the same directory with the following contents:
C:\python23\python YOURSCRIPTNAME.py
Then double click that batch file. Or, you can simply run that line in the command prompt while your working directory is the location of your script.
Since you seem to be on windows you can do this so python <filename.py>. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.
use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.
Your command should include the url parameter as stated in the script usage comments.
The main function has 2 parameters, url and out (which is set to a default value)
C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
If you want to run .py files in Windows, Try installing Git bash
Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads"
File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split
ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!

Categories