Run a Python script without the IDE - python

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

Related

Use command prompt from python

I write a python scripts that after execute some db queries, save the result of that queries on different csv files.
Now, it's mandatory to rename this file with the production's timestamps and so every hour i got new file with new name.
The script run with a task scheduler every hour and after save my csv files I need to run automatically the command prompt and execute some command that includes my csv files name in the path....
Is it possible to run the cmd and paste him the path of csv file like a variable? in python I save the file in this way:
date_time_str_csv1 = now.strftime("%Y%m%d_%H%M_csv1")
I don't know how to write automatically the different file name when i call the cmd
If I understand your question correctly, one solution would be to simply execute the command-line command directly from the Python script.
You can use the subprocess module from Python (as also explained here: How do I execute a program or call a system command?).
This could look like this for example:
csv_file_name = date_time_str_csv1 +".csv"
subprocess.run(["cat", csv_file_name)
You can run a system cmd from within Python using os.system:
import os
os.system('command filename.csv')
Since the argument to os.system is a string, you can build it with your created filename above.
you can try using the subprocess library, and get a list of the files in the folder in an array. This example is using the linux shell:
import subprocess
str = subprocess.check_output('ls', shell=True)
arr = str.decode('utf-8').split('\n')
print(arr)
After this you can iterate to find the newest file and use that one as the variable.

VS terminal just outputting two directories?

I am writing a small script to create an Excel workbook with new sheets.
But every time I try and run it the terminal window opens and just shows:
& "C:/Program Files/Python39/python.exe" "c:/Users/Jerome/Desktop/VS Code Projects/Python/Excel workbook/excel_sheet.py"
I am not sure what this means?
import xlwt
from xlwt import Workbook
# This creates the workbook
wb = Workbook()
# the add_sheet() method is used to create a sheet
sheet1 = wb.add_sheet('Sheet 1')
sheet1.write(1, 0, "Chris Smith")
# this saves the workbook
wb.save('new-sheet.xlsx')
It is not an error. It is a command that runs your code with python interpreter. For example if you put a print('end') at the end of your code you can see the print result after this line.
I assume you run the code by clicking on the top right run button in vscode or some other editors. They write this command in the terminal to run your code with python. It is not an error.
"C:/Program Files/Python39/python.exe" this part is the path to python exe file. and "c:/Users/Jerome/Desktop/VS Code Projects/Python/Excel workbook/excel_sheet.py" is the path to the file of your code.
When you run this code open the folder your code exists in. You have to see a new file named new-sheet.xlsx been created. (also I ran your code everything is ok).
If you have any questions please ask.

Call all files from a menu

I've got a task to do that is crushing my head. I have five .py documents and I want to make a menu in another .py so I can run any of them by introducing a string inside an input() but don't really see the way to do that and I don't know if there is somehow I can.
I have tried import every file to the 6th file but I don't even know how to start.
I would like it just to be seen as simple as it can sound, but yet I find it really hard.
If you just want to run them, then try this:-
import os
file_path = input("Enter the path of your file = ")
os.system(file_path)
If the file that you are trying to execute is not in the current
directory, i.e. doesn't exist in the same folder as the currently
executing python file, then you have to provide it's full path.
Path Format:-. C:\Users\lmYoona\OneDrive\Desktop\example.py
If the python file you are trying to execute is in the same directory as
the currently executing python file, then abstract name will also
work
Path Format:- example.py
P.S.:- I would only recommend this method if all you want is just to execute the other python file, rather then importing stuff from it.

How to open any program in Python?

Well I searched a lot and found different ways to open program in python,
For example:-
import os
os.startfile(path) # I have to give a whole path that is not possible to give a full path for every program/software in my case.
The second one that I'm currently using
import os
os.system(fileName+'.exe')
In second example problem is:-
If I want to open calculator so its .exe file name is calc.exe and this happen for any other programs too (And i dont know about all the .exe file names of every program).
And assume If I wrote every program name hard coded so, what if user installed any new program. (my program wont able to open that program?)
If there is no other way to open programs in python so Is that possible to get the list of all install program in user's computer.
and there .exe file names (like:- calculator is calc.exe you got the point).
If you want to take a look at code
Note: I want generic solution.
There's always:
from subprocess import call
call(["calc.exe"])
This should allow you to use a dict or list or set to hold your program names and call them at will. This is covered also in this answer by David Cournapeau and chobok.
You can try with os.walk :
import os
exe_list=[]
for root, dirs, files in os.walk("."):
#print (dirs)
for j in dirs:
for i in files:
if i.endswith('.exe'):
#p=os.getcwd()+'/'+j+'/'+i
p=root+'/'+j+'/'+i
#print(p)
exe_list.append(p)
for i in exe_list :
print('index : {} file :{}'.format(exe_list.index(i),i.split('/')[-1]))
ip=int(input('Enter index of file :'))
print('executing {}...'.format(exe_list[ip]))
os.system(exe_list[ip])
os.getcwd()+'/'+i prepends the path of file to the exe file starting from root.
exe_list.index(i),i.split('/')[-1] fetches just the filename.exe
exe_list stores the whole path of an exe file at each index
Can be done with winapps
First install winapps by typing:
pip install winapps
After that use the library:
# This will give you list of installed applications along with some information
import winapps
for app in winapps.list_installed():
print(app)
If you want to search for an app you can simple do:
application = 'chrome'
for app in winapps.search_installed(application):
print(app)

Apple Automator process csv files and create new files

Is it possible to loop through a set of selected files, process each, and save the output as new files using Apple Automator?
I have a collection of .xls files, and I've gotten Automator to
- Ask for Finder Items
- Open Finder Items
- Convert Format of Excel Files #save each .xls file to a .csv
I've written a python script that accepts a filename as an argument, processes it, and saves it as p_filename in the directory the script's being run from. I'm trying to use Run Shell Script with the /usr/bin/python shell and my python script pasted in.
Some things don't translate too well, though, especially since I'm not sure how it deals with python's open('filename','w') command. It probably doesn't have permissions to create new files, or I'm entering the command incorrectly. I had the idea to instead output the processed file as text, capture it with Automator, and then save it to a new file.
To do so, I tried to use New Text File, but I can't get it to create a new text file for each file selected back in the beginning. Is it possible to loop through all the selected Finder Items?
Why do you want this done in the folder of the script? Or do you mean the folder of the files you are getting from the Finder items? In that case just get the path for each file passed into Python.
When you run open('filename','w') you should thus pass in a full pathname. Probably what's happening is you are actually writing to the root directory rather than where you think you are.
Assuming you are passing your files to the shell command in Automator as arguments then you might have the following:
import sys, os
args = sys.argv[1:]
for a in args:
p = os.path.dirname(a)
mypath = p + "/" + name
f = open(mypath, "w")

Categories

Resources