Compiling a script in. exe that uses InstaPy - python

I'm writing a bot for IG using the Tkinter and InstaPy libraries. If you run the script with an interpreter, everything works correctly, but after compiling it in .exe using pyinstaller, the console returns this error after starting the browser:
FileNotFoundError: [WinError 3]The system cannot find the specified path: 'C:\Users\DANILG~1\AppData\Local\Temp_MEI12802\instapy\firefox_extension\manifest.json'.
(In the console, the error text is written in Russian, here is the translation)
At first, it seemed to me that this was due to escaping the "/" in the file path. But in addition, the user name changes in the path (it must be DanilGolovzin, while the path specifies DANILG~1). Well, if you still try to go to the desired directory, ignoring the escaping and mismatch of the user name, then _MEI71162 will not have the instapy folder.
console

The problem occures because of pyinstaller. When you build the script, in "browser.py"
ext_path = os.path.abspath(os.path.dirname(__file__) + sep + "firefox_extension")
we have ext_path like that. It works when you run it as a .py but when you build it, I think it runs in Temp folder and try to find it in that folder. So when it doesn't find, an error raise. I've solve with changing "browser.py" like that:
def create_firefox_extension():
ext_path = os.path.abspath(os.path.dirname(__file__) + sep + "firefox_extension")
# safe into assets folder
zip_file = use_assets() + sep + "extension.xpi"
files = ["manifest.json", "content.js", "arrive.js"]
with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED, False) as zipf:
for file in files:
try:
zipf.write(ext_path + sep + file, file)
except :
new_ext_path = os.getcwd()+sep+"firefox_extension"
zipf.write(new_ext_path + sep + file, file)
return zip_file
After making these changes, I've coppied the firefox_extension to .exe folder and it runs without any problem.

Related

How to make this file execute on another computer - how to have a changeable path?

I am trying to make a keylogger, it works on my computer but when i turn it into an executable it gives me an error "Python failed to execute script keylogger" I think its a path problem because its static and every computer have a diffrent directory, i am a beginner i could use some help.
files = ["log.txt", "info.txt", "clipboard.txt", "screenshot.png"]
dir_path=r"C:/Users/messa/Desktop/Python keylogger/"
##This function to take a screenshot---------------
def takess():
im = ImageGrab.grab()
im.save(dir_path+ "/" + "screenshot.png")
## i have multiple functions tell me if this is not enough .
My solution idea: I tried to check for this path if it does not exist i'll create it, after creating the directory i want to create the files in this directory, but it gives me a permission error " PermissionError: [Errno 13] Permission denied:"
extend = "\\"
dir_path="C:\\Users\\Default\\AppData\\Local"
Path(dir_path).mkdir(parents=True, exist_ok=True)
files = ["log.txt", "info.txt", "clipboard.txt", "screenshot.png"]
for file in files:
f= open(dir_path + extend + file, "w+")
f.close()
You can use pathlib module to get a stored location
import pathlib
dir_path = pathlib.Path().absolute()

Include poppler in exe file with pyinstaller

I tried to write a simple program for converting PDF files to JPG. The main idea is a simple .exe file that will find all PDF files in the same directory, and after converting them to JPG put them in the new folder.
And I did it! Using pdf2image, my program doing exactly as I want and as .py and as .exe. But, after running this program on another PC I got an error with popper >following Cmd screenshot
So, I understand, the program tries to find a popper. And sure on another PC program can't find it.
I tried --hidden-import, and --onedir, --onefile e.t.c.
Also saw some similar problem here, as:
PyInstaller and Poppler
Include poppler while generating an application using pyinstaller
But, or I do something wrong, or can't clearly understand how to do solutions in this questions.
What should I do?
#P.S. Maybe, there is a better library or module to create this kind of program?
Whole code:
import os
import pdf2image
from pdf2image import convert_from_path
from inspect import getsourcefile
from pdf2image.exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
# Create output direction
# Direction of executable file
script_dir = os.path.abspath(getsourcefile(lambda:0))
# print(script_dir)
output_dir = 'JPG'
# List for files which wasn't converted
error_list = []
# If path don't exist - create
if not os.path.exists(output_dir):
os.makedirs(output_dir)
#print('Path has been created', "\n")
else:
pass
#print('Directory exist', "\n")
# Show all files in directory
file_list = os.listdir()
print(file_list, "List of files")
for file in file_list:
try:
# print(file)
pages = convert_from_path(file, dpi=300, fmt='jpg', output_folder=output_dir, output_file=file)
except Exception as e: print(e)
print("File wasn't converted:", "\n")
if len(error_list) == 0:
print(0, "\n")
else:
for f in error_list:
print(f)
input("Done! Press Enter")

No such file error when changing permissions of newly created HTML file in Python

I am running a process that downloads an html file using Selenium, Chromedriver and Ubuntu and then attempts to change the permissions of that file to 777. But it fails with "no such file or directory" error.
The thing is this, because I connect to a VPN using openvpn and disconnect several times during the process, I need to run it with root access.
I therefore have this shell script that I run using sudo bash ./nameofscript.sh:
#!/bin/bash
source ~/imageTextAlgorithms/bin/activate
python ~/imageTextAlgorithms/DownloadURLs.py
After connecting to the VPN and downloading the desired file using Selenium, I run the following to save the file and change permissions:
filename = os.path.join(parentdir,"data","HTML",get_random_string(10))
pyautogui.hotkey('ctrl', 's')
time.sleep(1)
pyautogui.typewrite(filename)
pyautogui.hotkey('enter')
call('sudo chmod 777 ' + filename + ".html", shell=True)
call('sudo chmod -R 777 ' + filename + "_files", shell=True)
Here parentdir is the full absolute path to the ~/imageTextAlgorithms directory where my code is located, and get_random_string(n) generates a random string of n lowercase characters, and I use pyautogui in order to make the browser download all images and css when saving, as opposed to just saving the html source file.
Those calls (the call function is from subprocess) give me a no such file error, but if I make the exact same call from an OS Command line it is successful. Also, I already tried using the python function os.chmod with no success.
Why is this happening? What am I doing wrong?
As suggested by furas in comments, it was a timing issue.
It turns out that there is a wait time between pyautogui pressing enter to the save dialog box and the files being in the system, as chrome downloads everything again when you save the page.
So I changed the calls to sudo chmod for this and now it works as expected:
while True:
try:
os.chmod( filename + ".html",0o777)
os.chmod( filename + "_files",0o777)
for dirpath, dirnames, filenames in os.walk( filename + "_files"):
for dirname in dirnames:
path = os.path.join(dirpath, dirname)
os.chmod(path, 0o777)
for filename in filenames:
path = os.path.join(dirpath, filename)
os.chmod(path, 0o777)
break
except Exception as e:
sleep(1)

Python os cannot get path to Desktop on One Drive

I am trying to get user's path to Desktop by using the following code:
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
d = datetime.datetime.today()
newpath = desktop + '\\New_folder' + str(d.day) + '_' + str(d.month) + '_' + str(d.year)
if not os.path.exists(newpath):
os.makedirs(newpath)
print('Desktop folder created: ' + newpath)
For most users that works, but I recently got a case of a user who has everything on One Drive and their path is: 'C:\Users\User1\OneDrive - CompanyName\Desktop'.
For these users, the script fails with this message:
FileNotFoundError: [WinError 3] The system cannot find the file specified 'C:\\Users\\User1\\Desktop\\New_folder_16_3_2020
How do I point python to their actual Desktop path, so that I can then work with that folder?
I suspect the reason for yours is that, make sure that you're accessing the directory through OneDrive instead of following the path to the desktop immediately from the user. So instead of this
C:\\Users\\User1\\Desktop\\New_folder_16_3_2020
it would be something like this
C:\\Users\\User1\\Desktop\\OneDrive\\New_folder_16_3_2020
I would recommend you to add a try/catch statement that if fails prepends/appends the oneDrive keyword to the path.

Code that only execute once, Python Startup folder

Hey and thanks for all of your answers. I try to write a piece of python code that only executes once, (first time the program is installed) and copies the program into the windows startup folders.
(C:\Users\ USER \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup)
That's the code i wrote for this. (Please don't judge me. I know it's
very shitty code. But I'm very new to coding. (this is the second
little program i try to write)
import os
import shutil
#get username
user = str(os.getlogin())
user.strip()
file_in = ('C:/Users/')
file_in_2 = ('/Desktop/Py Sandbox/test/program.py')
file_in_com = (file_in + user + file_in_2)
folder_seg_1 = ('C:/Users/')
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup')
#create FolderPath
folder_com = (folder_seg_1 + user + folder_seg_2)
shutil.copy2(file_in_com, folder_com)
Because i got an error, that there is no such internal, external,
command, program or batch file named Installer. I tried to generate a batch file with
nothing in it that executes when the installation process is finished.(But the error is still there.)
save_path = 'C:/Windows/assembly/temp'
name_of_file = str("Installer")
completeName = os.path.join(save_path, name_of_file+".bat")
file1 = open(completeName, "w")
file1.close()
The main idea behind this that there is my main Program, you execute
it it runs the code above and copies itself to the startup folder.
Then the code the whole installer file gets deleted form my main
program.
import Installer
#run Installer File
os.system('Installer')
os.remove('Installer.py')
But maybe there's someone out there who knows the answer to this problem.
And as I said earlier, thanks for all of your answers <3.
BTW I'm currently using Python 3.5.
Okay guys now I finally managed to solve this problem. It's actually not that hard but you need to think from another perspective.
This is now the code i came up with.
import os
import sys
import shutil
# get system boot drive
boot_drive = (os.getenv("SystemDrive"))
# get current Username
user = str(os.getlogin())
user.strip()
# get script path
script_path = (sys.argv[0])
# create FolderPath (Startup Folder)
folder_seg_1 = (boot_drive + '/Users/')
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup')
folder_startup = (folder_seg_1 + user + folder_seg_2)
#check if file exits, if yes copy to Startup Folder
file_name = (ntpath.basename(script_path))
startup_file = (folder_startup + ("/") + file_name)
renamed_file = (folder_startup + ("/") + ("SAMPLE.py"))
# checkfile in Startup Folder
check_path = (os.path.isfile(renamed_file))
if check_path == True:
pass
else:
shutil.copy2(script_path, folder_startup)
os.rename(startup_file, renamed_file)
This script gets your username, your boot drive, the file location of
your file than creates all the paths needed. Like your personal
startup folder. It than checks if there is already a file in the
startup folder if yes it just does nothing and goes on, if not it
copies the file to the startup folder an than renames it (you can use that if you want but you don't need to).
It is not necessary to do an os.getenv("SystemDrive") or os.getlogin(), because os.getenv("AppData") already gets both. So the most direct way of doing it that I know of is this:
path = os.path.join(os.getenv("appdata"),"Microsoft","Windows","Start Menu","Programs","Startup")

Categories