I need to run the desired program in an application I am developing.
I know I can run cmd commands with the code os.system in Python's built-in OS module.
But when I run the start command with cmd and try to open an application that is not on the computer, windows shows me an ugly pop-up message. To prevent this, I need to scan the files on the computer and find out if the desired program exists before running the "start" command. How can I do that?
you can use:
os.path.exists(directory)
To check if a file exists in python.
However, it is better to use:
os.path.isfile(directory)
In this case so that you wont get the error message with the path does not point to a file, but still exists.
Related
I will try to be brief!
For whatever reason, I couldn't make the entirety of my program in python, so I had to outsource one specific task to php (a language I do not know very well). As the python program runs, it is supposed to trigger the php program to run, and then do a few things afterwards which is not a problem.
It seems to me that, to be able to run something through python, you need it to be able to run through cmd first, and then you can make python use cmd to run the program. I had a few issues there, because the programs are on different drives, and the php program references other files and locations in the same directory and in sub-directories to where it is, this means I couldn't execute in one line of cmd, but first had to change directory, to then execute the php program from the folder it's in. Because my command wasn't just one line, I made a batch file containing all the steps.
My current working method is to open up cmd, change directory in cmd to where the php file is, and then run the php file. I had to add php to the "Environment Variable Path" to be able to do this. Here is the batch file that currently works when run by me:
cd /d C:
cd C:\Users\UserMain\Desktop\php\colorextract
php (2).php
When I double click this bat file, from my E drive, it successfully executes the php program. But when I tell python to execute the batch file, that is where things go wrong.
Here is my python code, apologies for the name of the bat file:
import os
os.system('cmd /k "bitch.bat"')
The resultant cmd window then goes thru the steps of the batch file: 1) it changes to the right directory, 2) it is unable to execute the php file because:
'php' is not recognised as an internal or external command, operable program or batch file.
Now, this is the standard error you get if you were to try running a php program without having added php to the "Environment Variable Path", I know this because I went through that same thing. But if I manually open a cmd window, not administrative or anything, I can 1) successfully perform the steps outlined in batch file, and program runs, and 2) I can even run the bat file, and that also runs the program.
The cmd window opened by python does not seem to be able to reference the "Environment Variable Path", or it is for another reason somehow handicapped against being able to do all the things that a normal cmd widow can. How can this be fixed?
Thanks in advance to anyone who reads this!
Edit: I found that python had not detected the changes I made to the environment variables the day before, hence why python's cmd was giving the exact error that not having php in the environment variable gives. After I restarted my computer, my code worked. Thank you to #Gerhard and #Aaron Junker for making me think much harder about this issue.
so I found a command that can be run after importing os.
print(os.environ)
I ran this, and it told me that Python could not see that php had been added to the environment variables, well, more likely that python did not have the most up to date information regarding what was in the path variable(s).
Restarting my computer made the changes kick in, and now my original code works. Whilst I do feel very stupid, I'm just happy that this is resolved.
This seems to me like both instances use different environment variables.
Open
System Properties -> Advanced -> environment variables and look that PHP is in the PATH variable in user variables and in System variables.
I'm running windows
I've got a python script that works as expected when I run it from my interpreter (Anaconda, i think that's an interpreter...), but when I run it from my file manager by double clicking the script ("script.py") I see a quick black screen flash, but nothing else. I'm using the input() function, so that's not the issue.
When I try the same thing with a simple test script, which is just the print() function and the input function, the command line or terminal screen, whatever the black screen is called, displays my printed string and closes only after I press enter.
I believe my issue has to do with file paths and working directories, but I'm a noob and I don't know how to solve this. My script declares this variable:
inv_folder=r"C:\Users\domin\OneDrive\Desktop\Test Folder" #folder to look for completed recipe files
which I believe is an absolute filepath. I then loop through the files in that folder and open and read them
for filename in os.listdir(inv_folder):
Main goal is to send my script to someone else's computer, and allow them to run it simply by double clicking on the file. Trying to do that on my computer and failing
Doubleclicking the .py file in Windows will generally run the file. In your case, if all your script is doing is looking for a directory and looping through files in it, it is quite possible that the script is working correctly, but that it is closing immediately upon completing the script.
E.g. if you have the following python file hello.py with the single line of code.
print("hello world")
If you doubleclick hello.py, you will only see a black window flash for a second, as the program runs and exits.
To check whether your code is working correctly or not, you are best to navigate to that folder in your command prompt and run the program within the command prompt. E.g. typing "hello.py" in the right folder will then show the correct output in the console.
Try running it in the console first, seeing if the code is giving any errors, and then working from there. But the behaviour you are describing is basically standard Windows behaviour and not necessarily an error.
If you need to pause the window after running, please see the following StackOverflow question and answers about "Python Equivalent to System('PAUSE')"
Have you considered to compile it?
You can compile it easily with pyinstaller and this command:
C:\<path_to_python>\Scripts\pyinstaller.exe --onefile -n <your script name> <your script path>
Of course replace the <> with the relevant paths for you.
I'm using pyinstaller to produce an exectuable for a python program. But, whenever I try to use a generated executable, I get a message window that reads "Failed to execute script ...".
The command I'm running is pyinstaller -w run.py. But, when run with the --debug option a different error is made apparent. "Failed to execute script pyiboot-1_bootstrap". After this error it kills the program.
I tried with the -F option and that did not change the outcome. All the files I created for the project are in the same directory. I did get warnings that dll's weren't being included but I resolved that.
Pyinstaller doesn't like the built in quit() function I was using.
Instead use sys.exit() to close the program.
See this question to see why sys.exit() is better practice for production code.
What I found useful was to make an exe of my .py script in console mode and then run it. For a very short period of time, I saw an error message in the console window. I had to screenshot it to read completely. So one of the imports was missing from the folder in which I had my script. I opened cmd from the location bar of that folder (by typing cmd there) and imported modules using pip install <module_name>.
Sorry for the long answer, I am a newbie.
I have a technical questions on python script.
I have developed code on my laptop and I want to move it in another one.
I installed python there, put when I try to double click on the .py file it is not working. Like the cmd screen goes away in a second.
Do you know why?
(if I open python through cmd it is working, so it is in path and it works)
What is probably happening is that there is an error being thrown on your new computer which causes command prompt to just instantly close.
The best way to run a python script is from an open command prompt/terminal. To do this open a command prompt and move into the directory of your python file. For example, if the file you are trying to run is located at C:\Users\Davide\PythonScripts, then open a command prompt and type
cd C:\Users\Davide\PythonScripts
Now your command window is in the folder that you want to run files out of.
Next you want to tell Python to run your script. This can be done by typing "python ". For example, if your script is name my_script.py, you would type
python my_script.py
What this is doing is telling your computer "open an instance of Python where you are running my_script.py." If there are any errors thrown, the command window will stay open after python closes and you can see what is going on.
Most likely, there is a package you are trying to import which it cannot find because it was not installed on your other computer. If at the top of your file you have "import xxx" or "from xxx import yyy" lines, your other computer might not be finding those modules and just throwing an error that instantly closes command prompt when you just double click the .py file.
I am using python 3 on Win10 and running my code by opening a Command Prompt window and typing the file location. However, the window closes as soon as the program terminates, and before I can read any errors.
Edit: This happens whether or not the program has errors.
Thank you.
Solution 1:
I just saw your comment:
When I do that, I recieve the error 'python' is not recognized as an
internal or external command, operable program or batch file
It looks like you haven't specified the path to the python executable: you need to add the python executable path to your Window's PATH variable. You can see how to do that here: Add Python to the PATH Environmental Variable (‘python’ is not recognized as an internal or external command)
Solution 2:
You can use input("enter to exit") at the end of your python code to keep the program alive. It would exit once you press enter.
You could also surround your code in a try except statement and place thr input() in the except to prevent the program from exiting when there are errors, but like #Kevin mentioned in the comments, this would catch run time errors but not syntax errors.
Solution 3:
You can write errors or anything information you want to a file such as log.txt for example, and then read that log file once the code finishes running e.g. how to write to a file in Python
FWIW, I have several Python versions on my Windows system, so I don't want to add any Python directories to my path permanently.
Code for each version is in a separate folder (e.g. 'py37'), with a subfolder for each project e.g. 'myProject'.
In py37, there's a batch file called pyEnv.bat with this content:
#echo off
path=%path%;C:\Python37\;C:\Python37\Scripts\
cd.
cmd
In Windows explorer, I head over to the project folder I want to work in, click in the address bar and type ..\pyEnv. That launches a DOS-box, in which I now can do python myproject.py. You can see print() output, errors, and so on.
You can up-arrow to try different modules, having typed them first.
Once you quit the DOS-box, your path is back to normal again.