Calling Python script in excel as executable - python

I am currently developing a tool for a client that interfaces with both python 2.7 and excel 2013 and as a result running into a problem.
As background, I have a python code I want to run as a executable. The client doesn't have python on their computers so it's vital that the exe runs without .py. I've converted the script from a .py to a .exe with py2exe. Then I am trying to call that .exe with VBA. When the macro runs it looks like it pulls up the command prompt for a second but it doesn't run the .exe. When I go into the directory and double click the .exe however, it runs fine and outputs what I want it to.
Below is my code in VBA:
Dim folderPath As String
folderPath = Application.ActiveWorkbook.Path
ChDir folderPath
Dim stAppName As String
stAppName = folderPath & "\dist\MAT.exe"
Call Shell(stAppName, 1)
Not sure if my Shell needs any other inputs
Any help would be appreciated!

this is an indirect answer more to help you figure out what might be wrong
in your main file put your program in a main function (you dont have to call it main... you can call it whatever)
def main():
#do whatever
then when you run it if its main do this
if __name__ == "__main__":
try:
main()
finally:
raw_input("Hit enter To Close...")
this will guarantee your window to stay open even if there is an uncaught error

Related

If an error occurs in code execution, focus on the Visual Studio Code window that the code running

I open my VS Code, open my project folder and put my code to run a Python file in loop and I'm going to do other activities on the computer, the VS Code window is in the background.
But the code encounters an error, at this point I would like the Visual Studio Code window running this code overlay all other windows and appear on the screen with focus.
If I want to create a shortcut that I click and it opens VS Code directly in the project folder, I need to put the path of the VS Code executable and after them put the path of the project folder:
"C:\Users\Computador\AppData\Local\Programs\Microsoft VS Code\Code.exe" "C:\Users\Computador\Desktop\Python
So I tried to use it:
import subprocess
from time import sleep
def main() -> None:
while True:
try:
a = 1
b = 0
c = a/0
except:
subprocess.Popen([r'"C:\Users\Computador\AppData\Local\Programs\Microsoft VS Code\Code.exe" "C:\Users\Computador\Desktop\Python'])
break
sleep(60)
if __name__ == '__main__':
main()
But get this error:
PermissionError: [WinError 5] Access Denied
How should I proceed to avoid this error?
The error could be more clear, but it is trying to run the whole string as an executable, which doesn't exist (therefore there is no access to it)
To provide arguments to an executable, it's best to create a list.
subprocess.Popen([
r'C:\Users\Computador\AppData\Local\Programs\Microsoft VS Code\Code.exe',
r'C:\Users\Computador\Desktop\Python'
])

Run Python script when opened via VBA or .bat

I am trying to open a py script via VBA Excel.
The script is to interact with engineering software which undertakes finite elements analysis. The script can run directly from the py editor.
They prepared a Python library I have to import at the beginning of the script which also requires some password and log in credentials for the script to interact with that specific software.
I can open simple py scripts (such as the classic Hello World) via the Shell in VBA.
The script that I have prepared is more complex. When opening my script via VBA using the shell it flashes the cmd window and nothing happens.
Below is the subroutine I have coded in VBA to open the Python interpreter and Python script, for illustration: it returns error message 2.
Sub RunPythonScript()
Dim wsh As Object
Dim PythonExe, PythoScript As String
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Long
Dim pth As String
PythonExe = """C:\ProgramData\Bentley\Geotechnical\PLAXIS 2D CONNECT Edition V20\python\python.exe"""
PythoScript = """C:\Users\ukjfv001\Desktop\MyPython\MyAnalysis.py"""
pth = PythonExe & PythoScript
Set wsh = VBA.CreateObject("WScript.Shell")
errorCode = wsh.Run(pth, windowStyle, waitOnReturn)
If errorCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
End Sub
There is a lot of information online on how to run Python scripts.
In this forum: How to call python script on excel vba?. I have also created a bat file which I could open via VBA but, got the following error message:
C:\Users\ukjfv001\Desktop\MyPython>"C:\Users\ukjfv001\Anaconda3\python.exe" ""C:\Users\ukjfv001\Desktop\MyPython\MyAnalysis.py""
start
Traceback (most recent call last):
File "C:\Users\ukjfv001\Desktop\MyPython\MyAnalysis.py", line 16, in
from plxscripting.easy import * #call Plaxis scritping library
ModuleNotFoundError: No module named 'plxscripting'
Below is a bit of the Python code which I have to place at the top of the script in the SciTE editor (which comes with the engineering software).
From what I can see in the error message (above) and the bit of code below from plxscripting.easy import there is something I am not doing.
I am new to Python so usually I need practical examples to understand what is to be done.
from plxscripting.easy import * #callS engineering scritping library
inputport = 8888888
plaxispw = some_password
plaxis_path = C:\Users\ukjfv001\... #to here the software is intalled
plaxis_input = Plaxis.exe #software executable
if not process_exists(plaxis_input): #checkS if software is alreayd running
# first launch software
args = [os.path.join(plaxis_path, plaxis_input),"--AppServerPort={}".format(inputport),"--AppServerPassWord={}".format(plaxispw)]
inputprocess = subprocess.Popen(args)
# Initialize new_server with waiting time
s_i, g_i = new_server('localhost', inputport, password=plaxispw, timeout=10.0)
s_i.new()#starts a new Project
#after this point is where I have my Python script...```
I had a similar problem where I got an error running a python script from a scheduler (via running a file) even though it ran in my IDE. I also had to run it from a batch file to see the error, otherwise nothing happened. The issue was that python could not find the path to my custom libraries (which may be your issue, since the error is a library import). I think this can happen if you set your Python Path to custom libraries in your IDE and the environmental variables/ path are not also set (that is what you need to synchronize).
In Spyder, you just go to Tools: Python Path Manager in the menu and hit synchronize. I don't know what IDE you are using, but probably it also has a Python Path Manager if it isn't Spyder.

I'm trying to run a program I converted from .py to exe but it's giving me the error "failed to execute script 'filename'."

The script I wrote is very simple and does not require any external files for it to work. I also tested it before converting it to an executable file and it ran as expected. Pyinstaller is how I converted it.
This is the code
# Imports
from shutdown import *
def initiate_shutdown():
"""Activate the program by using this singular function"""
# Main code
shutdown(force=True, warning_off=False)
# Exectutes it
initiate_shutdown()
Try changing it to:
# Executes it
if __name__ == '__main__':
initiate_shutdown()

Pass a file to Python via the Right-Click 'Open With' context menu in windows, to then open in another program

I use a piece of software that when you close, saves your current configuration, however, next time I open the software by clicking on a file associated with it, it tries to run that file through the same configuration, which I don't want. I have therefore created a python script to first open up the app data for that program, reset the configuration back to default, and then open the program again.
This works fine if I just try to load the program without a file, but I would like to be able to click on a file associated with that program (usually I can just double click on the file to open it in the program), then use the 'open with' function in windows to select my script, and then open the file in the program once my script has cleared out the last configuration.
Currently, if I do this, it clears the configuration and opens the program but with no file loaded.
Essentially I am asking how I can pass the file to python, and then get python to pass that file to the third party application.
I am using the 'os.startfile('link to .exe') function to open the program, but how do I get the file path into python as an argument/string by clicking on the file and opening it with my script?
path = 'path/to/file/selected' # passed to python from selecting the file in windows explorer before starting script
# execute some code
os.startfile('path')
I'm a bit of a beginner when it comes to python so any help would be appreciated!
Using python 3.6 on windows 10
You can access command line arguments passed to your script using sys.argv. As long as you want to pass these arguments to some third-party application(which is an executable binary) you should use the subprocess module as os.startfile is meant to start a file with its associated application.
import sys
import subprocess
def main():
if len(sys.argv) == 1:
path = sys.argv[0]
subprocess.run(['/path/to/my.exe', path])
else:
print('Usage myscript.py <path>')
if __name__ == "__main__":
main()
If I understand your question correctly it could be done in the following fashion, relying on the subprocess module:
subprocess.Popen(["/path/to/application", "/path/to/file/to/open"])
See documentation for more details.

Printing output of python script to Windows console, when running via batch file

I have tried to look at other resources on SO but none seem to solve my problem:
Executing Python Script From Command Line is Hiding Print Statements
How do I write output in same place on the console?
Python script doesn't print output in command prompt
I have a .py script that I'm executing via a batch file. Within my .py script, I have a few different attempts at printing output to the console window. When I run the batch file and the console window pops up, I don't see the print output. I don't have any other problems with executing the program, and I've otherwise used python and batch files to generate file output, etc.
This is my .py script, I'm trying three different ways of writing output based on other SO articles:
import sys
# Attempt 1
print('hello')
# Attempt 2
sys.stdout.write('hello')
# Attempt 3
if __name__ == '__main__':
print('hello')
My batch file:
"C:\Program Files\Anaconda3\pythonw.exe" "\\*********\printTest.py"
PAUSE
My output, none of my desired 'hello' output displays. I've edited the location of my script but the directory has been triple checked and is correct:
C:\Windows>"C:\Program Files\Anaconda3\pythonw.exe" "\\********\printTest.py"
C:\Windows>PAUSE
Press any key to continue . . .
How do I get 'hello' to print to the console?
You're running "pythonw.exe", which is for graphical user interface (GUI) scripts, not console scripts. Run "python.exe" to inherit CMD's console for standard I/O.

Categories