Download and Install a .exe File using Python - python

I wanna create an auto-updater for my project which downloads and installs a file from the internet. I have done how I can download the file to my desired location with a desired name. The place where I am stuck is how I can install the file.
The code so far I have written:
from urllib.request import urlretrieve
import getpass
url = 'https://sourceforge.net/projects/artigence/files/latest/download'
print('File Downloading')
usrname = getpass.getuser()
destination = f'C:\\Users\\{usrname}\\Downloads\\download.exe'
download = urlretrieve(url, destination)
print('File downloaded')
And the file is downloaded to my downloads folder. Now, how can I install the .exe file using python?

You will need to use the subprocess module to execute the .exe files.
import subprocess
cmd = "{download location} batch.exe"
returned_value = subprocess.call(cmd, shell=True) # returns the exit code in unix
print('returned value:', returned_value)
refer
I strongly suggest not to use pyautogui for this.

Related

How to zip all outputs (*.csv and *.tiff) in jupyter notebook

I use this command
! zip -r results.zip . -i *.csv *.pdf
in Jupyter Notebook(Python 3.7.10) in order to zip all the output files. But, it shows
zip' is not recognized as an internal or external command, operable program or batch file.
Can anyone suggest what I miss?
I think you are trying to use,os.system():
If you are using linux
import os
os.system("zip -r results.zip . -i *.csv *.pdf")
#OR
import subprocess
subprocess.Popen("zip -r results.zip . -i *.csv *.pdf")
If you aren't using linux, in windows. There is library called zipfile, you can use it:
from zipfile import ZipFile
import os
filesname=os.listdir("<path or empty") # Or you can alternately use glob inside `with` ZipFile
# Empty means working folder
with ZipFile('output.zip', 'w') as myzip:
for file in files:
if file.endswith(".csv") and file.endswith(".pdf"):
myzip.write(file)
On modern Windows the Zip tool is Tar
It is not well documented nor as easy to use as most 3rd Party zippers thus you would need to custom wrap your OS call.
generally the following should be good enough
Tar -a -cf results.zip *.csv *.pdf
However if there are not one or other type the response will complete for the valid group, but with a very cryptic response:-
Tar: : Couldn't visit directory: No such file or directory
Tar: Error exit delayed from previous errors.

Executing .py file from Command Prompt raises "ImportError: no module named geopandas"- Script works in Spyder (using anaconda)

I have a python script that accomplishes a few small tasks:
Create new directory structure
Download a .zip file from a URL and unzip contents
Clean up the data
Export data as a .csv
The full .py file runs successfully giving desired output when in Spyder, but when trying to run the .py from Command Prompt, it raises "ImportError: no module named geopandas"
I am using Windows 10 Enterprise version 1909, conda v4.9.2, Anaconda command line client v 1.7.2, Spyder 4.2.3.
I am in a virtual environment with all the needed packages that my script imports.
The first part of my script only needs os and requests packages, and it runs fine as its own .py file from Command Prompt:
import os
import requests
#setup folders, download .zip file and unzip it
#working directory is directory the .py file is in
wd = os.path.dirname(__file__)
if not os.path.exists(wd):
os.mkdir(wd)
#data source directory
src_path = os.path.join(wd, "src")
if not os.path.exists(src_path):
os.mkdir(src_path)
#data output directory
output_path = os.path.join(wd,"output")
if not os.path.exists(output_path):
os.mkdir(output_path)
#create new output directories and define as variables
out_parent = os.path.join(wd, "output")
if not os.path.exists(out_parent):
os.mkdir(out_parent)
folders = ["imgs", "eruptions_processed"]
for folder in folders:
new_dir = os.path.join(out_parent, folder)
if not os.path.exists(new_dir):
os.mkdir(new_dir)
output_imgs = os.path.join(out_parent, "imgs")
if not os.path.exists(output_imgs):
os.mkdir(output_imgs)
output_eruptions = os.path.join(out_parent, "eruptions_processed")
if not os.path.exists(output_eruptions):
os.mkdir(output_eruptions)
if not os.path.exists(os.path.join(src_path,"Historical_Significant_Volcanic_Eruption_Locations.zip")):
url = 'https://opendata.arcgis.com/datasets/3ed5925b69db4374aec43a054b444214_6.zip?outSR=%7B%22latestWkid%22%3A3857%2C%22wkid%22%3A102100%7D'
doc = requests.get(url)
os.chdir(src_path) #change working directory to src folder
with open('Historical_Significant_Volcanic_Eruption_Locations.zip', 'wb') as f:
f.write(doc.content)
file = os.path.join(src_path,"Historical_Significant_Volcanic_Eruption_Locations.zip") #full file path of downloaded
But once I re-introduce my full list of packages in the .py file:
import os
import pandas as pd
import geopandas as gpd
import requests
import datetime
import shutil
and run again from Command Prompt, I get:
Traceback (most recent call last):
File "C:\Users\KWOODW01\py_command_line_tools\download_eruptions.py", line 17, in <module>
import geopandas as gpd
ImportError: No module named geopandas
I am thinking the problem is something to do with not finding my installed packages in my anaconda virtual environment, but I don't have a firm grasp on how to troubleshoot that. I thought I had added the necessary Anaconda file paths to my Windows PATH variable before.
The path to my virtual environment packages are in
"C:\Users\KWOODW01\Anaconda3\envs\pygis\Lib\site-packages"
echo %PATH% returns:
C:\Users\KWOODW01\Anaconda3\envs\pygis;C:\Users\KWOODW01\Anaconda3\envs\pygis\Library\mingw-w64\bin;C:\Users\KWOODW01\Anaconda3\envs\pygis\Library\usr\bin;C:\Users\KWOODW01\Anaconda3\envs\pygis\Library\bin;C:\Users\KWOODW01\Anaconda3\envs\pygis\Scripts;C:\Users\KWOODW01\Anaconda3\envs\pygis\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\McAfee\Solidcore\Tools\GatherInfo;C:\Program Files\McAfee\Solidcore\Tools\Scanalyzer;C:\Program Files\McAfee\Solidcore;C:\Program Files\McAfee\Solidcore\Tools\ScGetCerts;C:\Users\KWOODW01\AppData\Local\Microsoft\WindowsApps;C:\Users\KWOODW01\Anaconda3\Library\bin;C:\Users\KWOODW01\Anaconda3\Scripts;C:\Users\KWOODW01\Anaconda3\condabin;C:\Users\KWOODW01\Anaconda3;.
So it appears that the path to the directory where my pygis venv packages live are already added to my PATH variables, yet from Command Prompt the script still raises the "ImportError: no module named geopandas". Pretty stuck on this one. Hoping someone can provide some more troubleshooting tips. Thanks.
I figured out I wasn't calling python in command prompt before executing the python file.
The proper command is python modulename.py instead of modulename.py if you want to execute a .py file from the command prompt. Yikes. Let this be a lesson for other python novices.

Is there a way to write python code to download zip file from github?

I am trying to automate data download from github. Assume the file in github is in a zip folder. Is there a way to write a python code to download the entire zip folder?
I have used the request method but it does not work. The code can run without error but the file is clearly smaller than the original file and I cannot open it by double click with error message file is invalide
import requests
URL = 'https://github.com/XYZ/file.zip'
r = requests.get(url)
# open method to open a file on your system and write the contents
with open("file.zip", "wb") as code:
code.write(r.content)
one way to workaround is to run a shell command in Python to clone the file then unzip on local using Python code
from subprocess import check_output
cmd = '!git clone https://github.com/XYI/file.git C:/Users/UserName/Desktop/test'
check_output(cmd, shell=True).decode()

Can't run the script as .exe but It runs properly as py file

I downloaded pyinstaller in order to turn my python scripts into an executable program. When I run my code as python file there is only one mistake on the third line import win32crypt and it is showing this 'error unresolved import 'win32crypt' but it works properly.
But when I convert my script to application (.exe file) It doesn't work (Without any error message). My script is made to copy from Google Chrome email/password and after that to paste those information into an txt file.
I have already install pywin32 from console with this command: pip install pywin32.\
This is my code.
import os
import sqlite3
import win32crypt
f= open("logins.txt","w")
def closeChrome():
os.system("taskkill /im chrome.exe /f")
def connectDb():
dBpath=os.path.expanduser("~")+r'\AppData\Local\Google\Chrome\User Data\Default\Login Data'
connectionObj=sqlite3.connect(dBpath)
cursorObj=connectionObj.cursor()
statement="SELECT origin_url,username_value,password_value FROM logins"
cursorObj.execute(statement)
data=cursorObj.fetchall()
for url,username,password in data:
password=win32crypt.CryptUnprotectData(password)
f.write(f"url: {url}, username: {username}, password: {password[1].decode('utf-8')}\n")
print(f"url: {url}, username: {username}, password: {password[1].decode('utf-8')}\n")
print(".................................")
closeChrome()
connectDb()
Thanks :)

Shutil.move doesn't move files

I am trying to move PDF files from one folder to another using shutil.move. After I execute the script, python doesn't see them anymore, while they are still visible in Windows explorer. If I run the script again, python tells me there are no files. I have to run reverse script in order for python to see them. I use 64-bit Python v3.6.4 on Windows 10.
Command prompt with counts
import os, sys
import shutil
from os.path import join
Filez=0
PDFZ=0
filovi = os.listdir("C:/Users/Mirko1/pdfannots-master/NoGo")
for file in filovi:
Filez +=1
if file.endswith(".pdf"):
newdr=join('C:\\', 'Users','Mirko1','pdfannots-master','NoGo', file)
olddr=join('C:\\', 'Users','Mirko1','pdfannots-master', file)
PDFZ +=1
shutil.move(newdr, olddr)
print(Filez)
print(PDFZ)

Categories