Use Python to run a .exe file in Windows Command Prompt - python

I am trying to integrate an existing program into a developing Python 2.7 script. Currently the program can be successfully run by typing the following in the command prompt:
`C:\wisdem\plugins\JacketSE\src\jacketse\SubDyn\bin\SubDyn_Win32.exe C:\wisdem\plugins\JacketSE\src\jacketse\SubDyn\CertTest\Test04_TrialD3.txt`
This is all one line; the .txt file contains inputs needed by the .exe file. I have tried using both os.system("C:\wisdem\plugins\...) and
subprocess.Popen("C:\wisdem\plugins\...", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE).stdout.read()
to do this, but neither one is working. Also, I need the command prompt's outputs to be printed Python. Any help would be greatly appreciated!

import os
print os.popen(r'''echo "hello"''').read()
I would suggest putting the full command within the triple quotes, and attempting. This will execute the command, and then print the output.
Using a String literal with prefix r should help with any weird escape character issues you are experiencing.
Please note that there are security concerns when using the above code as well as os.popen being Deprecated since version 2.6. However, for a quick local script in 2.7, the above will suffice.

Related

why the same powershell command run on the powershell console but not using os.system?

I would like to include a command to create a 7zip archive withinin a Python script. Since I am working on Windows, I need to pass the command to the powershell console. I am planning to do it with os.system (I am aware that this is not the best way to do it and that I should use subprocess, but I really just need a quick fix and it would not be time effective for me to learn to use a new module in this context).
The following command works if run from the powershell console
&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch
So I recreate the same string within python like this:
cmdl = r"&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch"
The string is interpreted as follow:
"&'C:\\\\Program Files\\\\7-Zip\\\\7z' a -mx=0 X:/myarch.zip X:/myarch"
Now, if I copy-paste the above string within the powershell console, it runs without problems. However, if I run it within python using os.system(cmdl) I got the following error
"The filename, directory name, or volume label syntax is incorrect"
Why is this the case and how can I fix this issue ?
os.system is meant for executing cmd commands, cmd commands can be ran in powershell maybe after all powershell is a bit advanced but I'm sure that you can't run a cmd command in powershell, henceforth your code is not working.
However a creative solution for executing a powershell command from python(not using python) would be to write your command into a .ps file(powershell script)and then run it using os.startfile()(use this code: os.startfile("script.ps"))

Why does this Python subprocess command only work when shell=True on Windows?

I have a python script that involves multiple subprocess.call commands. I wrote the script on a Mac, and it runs perfectly. I just tried running it on Windows and I am baffled by an error.
The following command to call ImageMagick returns "exit status 4":
file1 = "D:/Temp/OCR_test/sample/images/crops/time_0011.png"
subprocess.call(['convert', file1, '-resize', '200%', file1])
Changing the command to the following works:
subprocess.call(['convert', file1, '-resize', '200%', file1], shell=True)
I'm a little wary of using shell=True because of the warnings in the documentation.
I also need the command to work on both Mac and Windows, and I am confused as to why it wouldn't work on Windows (I checked and the command does work using Windows CMD).
Interestingly, the following line worked earlier in the script (where file, lat_crop1, and croplat are defined variables):
subprocess.call(['ffmpeg', '-loglevel', 'panic', '-i', file, '-vf', lat_crop1, '-n', croplat])
I read this SO question and tried all the suggestions (shlex, variations of my command, etc...), but I still get the same result.
Anyone have any idea how I could modify that line so it can work without shell=True?
Also, what does "exit status 4" mean? I Googled and read so much documentation but found nothing about it.
EDIT: Based on the information provided in the answer, I changed to the command that was not working to subprocess.call(['mogrify', file1, '-resize', '200%', file1]) and that runs successfully in Python on Windows. Luckily ImageMagick provides mogrify as an alternative to convert.
I suspect you're calling C:\Windows\System32\convert.exe (NTFS/FAT partition converter) instead of imagemagick.
When shell=True, the path finds the convert.bat or convert.cmd script from imagemagick, but without it, the path can only find the .exe file, which is a completely different program, and you get error 4: invalid parameter.
In that particular case, it doesn't work even with an executable, because the "wrong" convert is located in a system path. shell=False only searches in system paths (python subprocess Popen environment PATH?). So that's bad luck that a program named convert is located in the system path.
Try to explicitly add .bat extension like this:
subprocess.call(['convert.bat', file1, '-resize', '200%', file1])
To know which executables are likely to be run you can type:
where convert
in a command prompt.
In your case (an executable), that could be workarounded by passing the absolute path of the executable you want to run.
Another way would be to copy/rename ImageMagick convert to imconvert. Which program calls itself convert and doesn't expect conflicts anyway ?
Or in that case, it's legitimate to leave shell=True, with a nice comment explaining that Microsoft left a confusing (and seldom used convert program in a system path for us to trip into)
Solutions are not pretty, at least there are some.

Python not recognizing the greater than sign?

I am using Python to create windows commands using subprocess.call(command) where command is a string I've generated for the Windows command. I need the results of my command to output to a .txt file so I use 2>> C:\Users\me\out.txt as part of command except Python does not seem to recognize the greater than character, >. I've tried using the Unicode value, u'\u003E' too.
[EDIT] If I copy command and paste it into my command prompt, then it will execute the command properly. Otherwise it won't work from my Python script.
Python has nothing to do with that.
If you do
subprocess.call("command 2>>out.txt", shell=True)
it is the shell which does this part of redirection.
If you don't work with the shell, it cannot work. In this case, you better do
with open("out.txt", "a") as outfile:
subprocess.call(["command"], stderr=outfile)
If you are using shell constructs such as redirection, you need the parameter shell=True.

Run python source file from PowerShell

I'm trying to learn python but have some problem running source files from power shell. When I type 'python' it opens up and I can type python commands directly in the shell. I think this is called interactive mode. But when I try to run/execute a source file I get an error message: It sayys: Syntax error: invalid syntax.
I use 'python myfile.py' when I try to execute the script.
If I run the same file from IDLE it works just fine. Ana idea what I'm doing wrong?
Here is myfile.py. I'm running python 2.7
# filename: myfile.py
while True:
s = raw_input('Enter something: ')
if s == 'Quit':
break
print 'Lenght of the string is', len(s)
print 'Done'
You might have more than one version of Python installed and the version IDLE is using is newer. To see what version of python you have you can type >python -V at a command line. If that version looks appropriate then you might need the full path to the file as the second parameter. E.g >python C:\myfile.py.
If you installed Python correctly there is always a chance that just typing the name of the script will run it with python. E.g. >myfile.py
I always find that adding C:\Python27 to the %PATH% variable and .PY to the %PATHEXT% variable makes running scripts easier. In this case just >myfile should work.
Edit after Update:
Typing just >python with no parameters opens python in 'interactive mode' which is different from the batch or scripting mode that your script is intended for. If executed with arguments the first argument is taken as the file path and further arguments are passed to the script in the sys.argv list.
You will need to put the full path of the Python executable within the command line in order for it to work. You could check and ensure that your python exe is included in your Path among your system variables.
Disclaimer: I don't know PowerShell, but I do know cmd.exe.
I don't know why python myfile.py doesn't work, but assuming that PowerShell bears at least some similarity to cmd.exe, the following should probably work: myfile.py. That's right, just enter the name of the Python script and hit enter.
If you started by typing "python" in powershell you will need to get out of that script.
If you are in python type:
quit()
then type
python myfile.py
This should work if your python is installed correctly.
Try to type this in Powershell:
$env:path="$env:Path;C:\Python33
After this, command
python yourfile.py
should work.
This my sound silly, especially coming from a beginner.
Just save the file on your desktop. Open up powershell and drag the file directly into powershell and it opens. kind of tedious but it works

Better way to execute ruby file using Python and How to get ruby console output when ruby file is run from python?

I am building a standalone using python.
This standaloone should execute a ruby file.
I have read this article - http://www.decalage.info/python/ruby_bridge
I have used os.system() which works well.
But I have an issue here.
If a ruby file has some error, file simply terminates without error.
Can you please let me know how to GET ruby console output so that I can display the same in my standalone.
you can use subprocess module
cmd="ruby myrubyscript.rb"
p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, errors = p.communicate()
then use the output variable
Just a note, your Python program will be dependent on whether you have Ruby installed or not. If possible, try to do everything in Python.

Categories