I wrote a simple script that decodes and sorts my scans (*.pdf) into Sharepoint. Everything works on my home PC where I tested it, but on my work pc it doesn't want to work. I want to drag and drop the pdfs (multiple sometimes) onto the script.
I printed out the path the script gets when the drag and drop starts.
Example: 20 ENS 02 0052.pdf turns into 207D51~1.PDF
Because somehow drag and drop doesn't work on this pc I had to create a shortcut to the script and add 'python' before the text in the target of the shortcut. ( But it also wont work if I just pass the file in console as argument
My debug script:
import sys
from pathlib import Path
import os
file = os.path.basename(sys.argv[1])
print(file)
os.system('pause')
The part of the original script i can show:
import os
import sys
import getopt
import sqlite3
from pathlib import Path
for pdf in sys.argv[1:]:
# extract filename and
file = os.path.basename(pdf)
# remove extension from full path
filename = file[:-4]
print("File: ".format(file))
print("Filename: ".format(filename))
# just for debug script would continue here
os.system("pause")
exit()
I tried it using a test script for debugging and passing the file as argument in console instead of drag and drop, but the same error happens. Worked on my work pc (also newest working version of python3).
Related
I would like to take a screenshot for my selenium driver and save it to a specific directory. Right now, I can run:
driver.save_screenshot('1.png')
and it saves the screenshot within the same directory as my python script. However, I would like to save it within a subdirectory of my script.
I tried the following for each attempt, I have no idea where the screenshot was saved on my machine:
path = os.path.join(os.getcwd(), 'Screenshots', '1.png')
driver.save_screenshot(path)
driver.save_screenshot('./Screenshots/1.png')
driver.save_screenshot('Screenshots/1.png')
Here's a kinda hacky way, but it ought to work for your end result...
driver.save_screenshot('1.png')
os.system("mv 1.png /directory/you/want/")
You might need to use the absolute path for your file and/or directory in the command above, not 100% sure on that.
You can parse the file path you want to the save_screenshot function.
As your doing this already a good thing to check is that os.getcwd is the same as the location of the script (may be different if your calling it from somewhere else) and that the directory exists, this can be created via os.makedirs.
import os
from os import path
file_dir = path.join(os.getcwd(), "screenshots")
os.makedirs(file_dir, exist_ok=True)
file_path = path.join(file_dir, "screenshot_one.png")
driver.save_screenshot(file_path)
If os.getcwd is not the right location, the following will get the directory of the current script..
from os import path
file_dir = path.dirname(path.realpath(__file__))
when i try
os.system("open " + 'myfile.xlsx')
i get the output '0'
similarly, trying
os.system("start excel.exe myfilepath")
gives the result 32512
I have imported os and system, and I'm on mac. How can I change this so it does actually launch that excel file? And out of curiosity, what do the numbers it prints out mean?
Thanks!
Just these two lines
import os
os.system("start EXCEL.EXE file.xlsx")
Provided that file.xlsx is in the current directory.
If you only want to open the excel application you could use subprocess:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
You can also use os and open a specific file:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")
If you on other hand want to open an excel file within python and modify it there's a number of packages to use as xlsxwriter, xlutils and openpyxl where the latter is prefered by me.
Another note, if you're on mac the excel application isn't .exe
On Windows 10, this works for me:
import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)
Copy-pasting any full path to a file in the command prompt (or passing it to os.system()) seems to work as long as you have permission to open the file.
I suppose this only works when Excel is selected as default application for the .xlsx extention.
I don't know about Mac OS, but if Windows Operating System is the case and provided the Microsoft Windows is properly installed, then consider using :
import os
os.system('start "excel" "C:\\path\\to\\myfile.xlsx"')
double-quotation is important for excel and C:\\path\\to\\myfile.xlsx ( where C just denotes the letter for the partition within the file system, might be replaced by D,E ..etc. ), and single-quotation is needed for the whole string within the os.system().
As in: How to open an Excel file with Python to display its content?
import os
file = "C:\\Documents\\file.xlsx"
os.startfile(file)
It opens the file with the default application.
If you want this to work with your most recent downloaded xlsx file, you can use the following:
import glob
import os
list_of_files = glob.glob('C:\\Downloads\\*.xlsx') *#note the .xlsx extension is needed to retrieve the last downloaded xlsx file.*
latest_file = max(list_of_files, key=os.path.getctime)
os.system(latest_file)
A minor improvement that handles spaces and explicitly uses Excel:
import os
file = "C:/Documents/file name with spaces.xlsx"
file_with_quotes = '"' + file + '"'
os.system('start "EXCEL.exe" {}'.format(file_with_quotes))
I'm automating my current reports and need help getting up and running.
I have a PS script that first fixes a csv file and then calls a python script. Within the python script I am importing modules that 'cannot be found' when the PS script runs.
I have tried importing the modules separately(but within the powershell script) to no avail. I have been trying to run from PyCharms using a powershell plugin. Even though I have tried running it in Powershell IDE and it produces the same error.
This is where it chokes. If I need to delve further please let me know and I will remove the sensitive information in the code and post it.
#POWERSHELL CODE
#start excel
$Excel = New-Object -Com Excel.Application
#make it visible (just to check what is happening)
$Excel.Visible = $true
#open file
$FilePath = 'file path here'
$Workbook = $Excel.Workbooks.Open($FilePath)
$Worksheets = $Workbooks.worksheets
#change column format type for DateTime issue in logs
$workbook.ActiveSheet.Columns.Item("X").NumberFormat = "yyyy-mm-dd hh:mm:ss"
$Output.ExitCode
#save doc and close excel
$ext=".csv"
$path="file here"
$workbook.SaveAs($path)
$workbook.Close
$Excel.DisplayAlerts = 'False'
$Excel.Quit()
$Output.ExitCode
python "file here" #calling python script here
$Output.ExitCode
#PYTHON CODE
import MySQLConnection2 as mc
import RedshiftConnection2 as rc
from Data_download2 import dict_to_csv
from os.path import join, basename
import datetime
import csv
import pandas as pd
import numpy as np
import sys
The python code generates several csv files that are needed for this report. Once I get past this choke I will need to call another python script and then alter the csv files.
Error Message > 'Import-Module : The specified module 'SQLalchemy' was not loaded because no valid module file was found in any module
directory.'
You cannot use Import-Module on python scripts and python modules.
I have a python script I wrote which uses tkinter and panda to:
choose a CSV file on the desktop,
imports in that data,
does some stuff,
exports the new dataframe created into a new csv.
Is there a way to run the program without the person needing to open up a python IDE and run it from there?
Currently when I try to just click and run the tester.py program I see the cmd_line (terminal) box open briefly and then close without my tkinter prompt or anything else.
My goal, or my ideal is that I wrote this program to help automate some tasks for non-technical coworkers. Is there a way that I could set up this program to just have them click on an exe file or a bat file and for the script to run, collect the User Input needed, and output the csv file like I want it to?
I've done some brief google searching but I haven't been able to find a clear answer.
import tkinter
import csv
import pandas as pd
from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
df1 = pd.read_csv(filename)
df2 = df1.query("STATE != 'NY'") # stores records not in NY
df3 = df1[df1["FIRST_NAME"].str.contains(" ", regex=True)] # stores records that have a space in the first name
dferror = [df2, df3]
dferror = pd.concat(dferror).drop_duplicates().reset_index() # merges dataframes, drops duplicates
dferror.to_csv("C:\errors.csv")
edited to add my import clauses
You can write a small executable script based upon your OS
Windows
Create a .bat file in which you need there needs to the command to execute your python file.
e.g. c:\python27\python.exe c:\somescript.py %*
For reference look here
MacOS / Linux
Create a .sh file which can be executed from your shell/terminal or by double clicking its sym link.
Your .sh file will look like
#!/bin/bash
python PATH_TO_YOUR_PYTHON_FILE
Then you must make it executable via running the following in terminal
chmod u+x PATH_TO_.SH_FILE
Alternatively you can create a symbolic link to your python file and make it executable. This symlink will be executable by double click.
To create a symlink:
ln -sf PATH_TO_.SH_FILE PATH_OF_SYMLINK
If you put just a name in place of PATH_OF_SYMLINK it will be created in your present directory.
Thanks to #abarnert, the solution was to use Pyinstaller which allows me to "freeze" the code into an exe file
when i try
os.system("open " + 'myfile.xlsx')
i get the output '0'
similarly, trying
os.system("start excel.exe myfilepath")
gives the result 32512
I have imported os and system, and I'm on mac. How can I change this so it does actually launch that excel file? And out of curiosity, what do the numbers it prints out mean?
Thanks!
Just these two lines
import os
os.system("start EXCEL.EXE file.xlsx")
Provided that file.xlsx is in the current directory.
If you only want to open the excel application you could use subprocess:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
You can also use os and open a specific file:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")
If you on other hand want to open an excel file within python and modify it there's a number of packages to use as xlsxwriter, xlutils and openpyxl where the latter is prefered by me.
Another note, if you're on mac the excel application isn't .exe
On Windows 10, this works for me:
import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)
Copy-pasting any full path to a file in the command prompt (or passing it to os.system()) seems to work as long as you have permission to open the file.
I suppose this only works when Excel is selected as default application for the .xlsx extention.
I don't know about Mac OS, but if Windows Operating System is the case and provided the Microsoft Windows is properly installed, then consider using :
import os
os.system('start "excel" "C:\\path\\to\\myfile.xlsx"')
double-quotation is important for excel and C:\\path\\to\\myfile.xlsx ( where C just denotes the letter for the partition within the file system, might be replaced by D,E ..etc. ), and single-quotation is needed for the whole string within the os.system().
As in: How to open an Excel file with Python to display its content?
import os
file = "C:\\Documents\\file.xlsx"
os.startfile(file)
It opens the file with the default application.
If you want this to work with your most recent downloaded xlsx file, you can use the following:
import glob
import os
list_of_files = glob.glob('C:\\Downloads\\*.xlsx') *#note the .xlsx extension is needed to retrieve the last downloaded xlsx file.*
latest_file = max(list_of_files, key=os.path.getctime)
os.system(latest_file)
A minor improvement that handles spaces and explicitly uses Excel:
import os
file = "C:/Documents/file name with spaces.xlsx"
file_with_quotes = '"' + file + '"'
os.system('start "EXCEL.exe" {}'.format(file_with_quotes))