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.
Related
Im trying to run a python script using Outlook Vba. When I run the below code. A python icon appears in the taskbar for a second and disappears. When in fact it should open a dialogue box and prompt me to enter folder name. After which it should run the rest of the script as usual.
Please help me run this script from outlook as I regularly do by double clicking the .py file.
Sub runpythonscript()
Dim Path As String
Path = "python C:\Doc Management\Exstream_Reconciliation.py"
Shell(Path)
End Sub
VBA (nor Outlook) doesn't provide anything for debugging such cases. The best what you could do is to add log statements to the python script where you could output everything what happens in the code. Analyzing log files you will be able to figure the cause of the problem.
You have a space in the file name. It must be quoted.
Ok this is the solution for anyone looking
Sub RunPyFileFromMacroViaCmd()
Dim Path As String
Dim filepath As String
filepath = """C:\Doc Management\Exstream_Reconciliation.py"""
Path = "cmd /k" & filepath
Shell (Path)
End Sub
I'm quite new to xlwings and I'm runing code from VBA in order to excecute a python script that writes some text in Excel.
The problem is when I run the VBA code, it seems to excecute python but my excel sheet doesn't change.
However, if I run the python script from python, it works just fine, even if the Excel file is already open.
VBA code is the following:
Sub Botón1()
Dim obj As Object
Dim pyexe, pyscript As String
Set obj = VBA.CreateObject("Wscript.Shell")
pyexe = """C:\Users\xxx\AppData\Local\Programs\Python\Python36-32\python.exe"""
pyscript = "C:\Users\xxx\Documents\Prueba.py"
obj.Run pyexe & pyscript, 1, True
End Sub
And python code is the following:
import xlwings as xw
wb = xw.Book('Libro1.xlsm')
sht = wb.sheets['Hoja1']
sht.range('A1').value = 'Hi!'
Both files (Libro1.xlsm and Prueba.py) are saved inside the same folder.
When I run excel macro it opens the cmd prompt but nothing happens in Excel spreasheet.
I have not installed xlwings add in, but I believe it is not necessary to do it, in order to do what I'm trying to do.
Can you please help me find what could be wrong?
I was reading this article:
https://devblogs.microsoft.com/scripting/how-can-i-get-the-command-window-to-stay-open-after-running-a-command-line-tool/
And it explains using .run is equivalent to calling Cmd.exe.
If I open cmd I just need to write my python file name with .py extension to run it.
So I figured out "pyexe" is not necessary.
The solution:
Sub Botón1_Haga_clic_en()
Dim obj As Object
Set obj = CreateObject("Wscript.Shell")
obj.Run "C:\Users\xxx\Documents\Prueba.py", 1, True
End Sub
I am learning Python through 'Automate the Boring Stuff With Python' First Edition. In chapter 12, pg 267, we are supposed to open a file called example.xlsx.
The author's code reads:
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
type(wb)
However, when I try to open this file, I get the following error (this is the last line of the error):
FileNotFoundError: [Errno 2] No such file or directory: 'example.xlsx'
I know this file exists, because I downloaded it myself and am looking at it right now.
I have tried moving it to the current location in which Python 3.8 is, I have tried saving it with my Automate the Boring Stuff files that I've been working on the desktop, and I have tried saving it in every conceivable location on my machine, but I continue getting this same message.
I have imported openpyxl without error, but when I enter the line
wb = openpyxl.load_workbook('example.xlsx')
I have entered the entire pathway for the example.xlsx in the parenthesis, and I continue to get the same error.
What am I doing wrong? How am I supposed to open an Excel workbook?
I still don't understand how I am doing wrong, but this one is incredibly infuriating, and I feel incredibly stupid, because it must be something simple.
Any insight/help is greatly appreciated.
Your error is unambigous — your file in a supposed directory don't exist. Believe me.
For Python is irrelevant, whether you see it. Python itself must see it.
Specify the full path, using forward slashes, for example:
wb = openpyxl.load_workbook('C:/users/John/example.xlsx')
Or find out your real current (working) directory — and not the one supposed by you — with commands
import os
print(os.getcwd())
then move your example.xlsx to it, and then use only the name of your file
wb = openpyxl.load_workbook('example.xlsx')
You may also verify its existence with commands — use copy/paste from your code to avoid typos in the file name / path
import os.path
print(os.path.exists('example.xlsx')) # True, if Python sees it
or
import os.path
print(os.path.exists('C:/users/John/example.xlsx')) # True, if exists
to be sure that I'm right, i.e. that the error is not in the function openpyxl.load_workbook() itself, but in its parameter (the path to the file) provided by you.
I notice that the extension of the example file is not the same as described in the book, is example.csv. I was facing the same frustration as you
I am trying to save the .xlsx file and using VBA as a wrapper to execute the python file. However, I can validate that python code runs, but somehow .xlsx file is not saved. When I run the same python file via IDE, it saves down the .xlsx file.
VBA code
Sub RunPython()
Dim shell As Object
Dim exepath, scriptPath As String
Set Shell = VBA.CreateObject("Wscript.Shell")
exePath = """C:\Program Files\...\python.exe"""
scriptPath = "C:\....\mymodule.py"
Python Script
import pandas as pd
import xlsxwriter
df = pd.DataFrame(np.random.randn(5,2),index=range(0,10,2),columns =list('AB'))
excel_file ='sample.xlsx'
writer = pd.ExcelWriter(excel_file,engine='xlsxwriter')
df.to_excel(writer,sheet_name='Data')
print ("file read")
writer.save()
writer.close()
Does that 'excel_file' have a path?
Does Python use a current directory and automatically add it to Excel file name?
If yes, do you know how to obtain it and can you look for .xlsx file there?
If not, how do you check if the .xlsx file has been saved? Where are you looking for?
Does Python raise any error?
I am looking to the code mostly like a VBA user...
I would suggest to send a message from Python, containing the current directory path. Supposing that the .xlsx workbook path has not somehow been defined and the code presented here does not include that part. Theoretically it should use the same current directory, but I think it is good to be checked...
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