Get the output of .exe file in Python3 on Windows - python

I've been trying to get the output of the following command 'manage-bde -status' which works fine on my windows cmd commande prompt, but by using a python program.The same command doesn't work on python subprocess, so I had to launch the manage-bde.exe file.
So my code looks like this now :
import os, platform, subprocess
################This part is only helpful for resolving 32 bit/64 bits issues##########
system_root = os.environ.get('SystemRoot', 'C:\\Windows');
if (platform.architecture()[0] == '32bit' and platform.machine() == 'AMD64'):
system32='Sysnative'
else:
system32='System32'
manage_bde = os.path.join(system_root, system32, 'manage-bde.exe')
print(manage_bde)
#######################################################################################
stdout=subprocess.check_output(['start',manage_bde,'-status'])
print('Output:'+stdout)
I'm launching it from cmd commande line, with Python 3.7.0. The problem is that I get the following output :
C:\WINDOWS\Sysnative\manage-bde.exe (this is from my print(manage_bde))
Traceback (most recent call last):
File "testCLI.py", line 13, in <module>
stdout=subprocess.check_output(['start',manage_bde,'-status'])
File "d:\Profiles\user\AppData\Local\Programs\Python\Python3\lib\subprocess.py", line 376, in check_output
**kwargs).stdout
File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 453, in run
with Popen(*popenargs, **kwargs) as process:
File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1155, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] Specified file was not found
I launch it from the D: Drive. Does anyone know what I missed ?

You probably need to run the script with administrator privileges.
If the file exists in the filesystem and you get FileNotFoundError: [WinError 2], you can test whether the the script has enough permissions to see the file with:
os.stat(manage_bde)

Yes I have enough permissions to see the file : the os.stat(manage_bde) is working.
I have changed my parameters like eryksun proposed :
stdout = subprocess.getoutput([manage_bde, '-status'])
Now I can launch the program (but only with a shell with administrator rights) and get the output, thank you !

Related

Subprocess No such file or directory error

As part of larger code, I am trying to make a function that calls to a latexmk compiler using subprocess, but I consistently get FileNotFoundError: [Errno 2] No such file or directory: 'latexmk': 'latexmk'
However, If I write the command directly in the terminal, everything works: latexmk --pdf test.tex
In case it is important, I am on MacOS Mojave 10.14.6, running python 3.6 spyder through anaconda
I have checked the following links:
https://askubuntu.com/questions/801493/python-subprocess-call-not-working-as-expected
OSError: [Errno 2] No such file or directory while using python subprocess in Django
Running Bash commands in Python
If anything there solves the problem, I missed it.
To make everyone's life easier, here's a link to a .tex file [you can use your own]:
https://drive.google.com/open?id=1DoJnvg2BmbRCzmRmqFYRVybyTQUtyS-h
Afer putting type latexmk to terminal it outputs:
latexmk is hashed (/Library/TeX/texbin/latexmk)
Here is the minimal reproducible example (you do need latexmk on your computer though):
import os, subprocess
def pdf(file_path):
cur_dir = os.getcwd()
dest_dir = os.path.dirname(file_path)
basename = os.path.basename(file_path)
os.chdir(dest_dir)
main_arg = [basename]
command = ["latexmk", "--pdf"] + main_arg
try:
output = subprocess.check_output(command)
except subprocess.CalledProcessError as e:
print(e.output.decode())
raise
os.chdir(cur_dir)
pdf("path to your .tex file")
I have a feeling that I am grossly misunderstanding the way subprocess works. Any ideas?
Update: In case neccessary, the full traceback:
Traceback (most recent call last):
File "<ipython-input-90-341a2810ccbf>", line 1, in <module>
pdf('/Users/sergejczan/Desktop/untitled folder/test.tex')
File "/Users/sergejczan/Desktop/Lab/subprocess error reproduction.py", line 23, in pdf
output = subprocess.check_output(command)
File "/anaconda3/lib/python3.6/subprocess.py", line 336, in check_output
**kwargs).stdout
File "/anaconda3/lib/python3.6/subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process:
File "/anaconda3/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/anaconda3/lib/python3.6/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'latexmk': 'latexmk'
New Update
Changing the output = subprocess.check_output(command) line with the hardcoded envirnoment that I got from echo $PATH worked wonderfully.
output = subprocess.check_output(command,env = {'PATH': '/anaconda3/bin:/Users/sergejczan/anaconda3/bin:/Users/sergejczan/Desktop/Lab/anaconda2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin'})
Would you think that there is a way to make the code find the PATH automatically?

Python Subprocess Class

I am a learning Python and was trying the subprocess class from the tutorial. The tutorial uses MAC OS hence used ls -l . Since i am using Windows OS i used dir -d instead.
import subprocess
subprocess.run(["dir", "-d"])
When ran the code in the terminal it prompts
C:\Users\Farhan Hasant\Desktop\HelloWorld>dir -d
Volume in drive C has no label.
Volume Serial Number is 8296-8904
Directory of C:\Users\Farhan Hasant\Desktop\HelloWorld
File Not Found
Again, when i ran the code using code runner in VS code it shows
[Running] python -u "c:\Users\Farhan Hasant\Desktop\HelloWorld\app.py"
Traceback (most recent call last):
File "c:\Users\Farhan Hasant\Desktop\HelloWorld\app.py", line 3, in <module>
subprocess.run(["dir", "-d"])
File "C:\Users\Farhan Hasant\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\Farhan Hasant\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 775, in init
restore_signals, start_new_session)
File "C:\Users\Farhan Hasant\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 1178, in _execute_child
startupinfo)[![enter image description here][1]][1]
FileNotFoundError: [WinError 2] The system cannot find the file specified
[Done] exited with code=1 in 0.213 seconds
My files
I am confused if I am doing it right. I would really appreciate your input on this. Thank you in advance.
dir is not a real command in Windows, it's something builtin in the "shell" so you need to tell subprocess to launch a shell before attempting to run the command:
import subprocess
subprocess.run(["dir", "/d"],shell=True)
Also, follow #jasonharper comment about using / instead of - for most Windows native commands

subprocess error in python

I am trying to run a praat file from python itself with subprocess but python(subprocess) can't seem to find the directory. I don't understand why since when I run the command in terminal, it works perfectly fine. Cant anyone guide me to where I am going wrong?
This is the subprocess code
import silex
import subprocess as sb
cmd_line = raw_input()
args = shlex.split(cmd_line)
p = sb.Popen(args)
When I run it with the input
Praat /Users/admirmonteiro/tmp/tmp.praat
this is the error that I get :
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/admirmonteiro/anaconda/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/Users/admirmonteiro/anaconda/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
As mentioned, I run the commands and they run fine in the terminal.
I have also tried to run subprocess.call but the same error occurs. I have also tried with with shell=True as an argument but that also outputs the same error.
Please Help !
Type the following in the shell to get the full path of the Praatapplication.
whereis Praat
Then use the full path in you python program.

Unable to run shell script from the Pydev environment in Eclipse

I am using Centos 7.0 and have installed Eclipse Kepler in the Pydev environment. I want to run a simple c shell script through Python using subprocess as follows:
import subprocess
subprocess.call(["./test1.csh"])
This c shell script executes in the terminal and also if I run command like "ls" or ""pwd then I get the correct output e.g.
subprocess.call(["ls"]) # give me the list of all files
subprocess.call(["pwd"]) # gives me the location of current directory.
But when I run subprocess.call(["./test1.csh"]), I get the following error:
Traceback (most recent call last):
File "/home/nishant/workspace/codec_implement/src/NTTool/raw2waveconvert.py", line 8, in <module>
subprocess.call(["./test1.csh"])
File "/usr/lib64/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied
Where am I going wrong? Please suggest
Make sure that the file test1.csh is executable. As Lukas Graf commented, also check the shebang (#!...) in the first line.
To confirm that, before run it through Python, run it in the shell.
$ ls -l test1.csh
...
$ ./test1.csh
The current working directory will be different from when you run it in the terminal. Specify the full path of the shell script. Or change the working directory configuration in the PyDev.
UPDATE
Prepend the shell executable:
import subprocess
subprocess.call(["csh", "./test1.csh"])

Python process.call() error

I have OSX and am running the python script out of the Unix shell
I'm running a python code that should open an application. I've been testing with Firefox.app and have been getting
Traceback (most recent call last):
File "/Users/brennan/Desktop/Coding/Wilix/wilix.py", line 453, in <module>
subprocess.call(["open -a "+cp2])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
My code is:
subprocess.call(["open -a "+cp2])
where cp2 is user input. (Firefox in this case)
if I cd into the programs directory and then do
open -a Firefox
firefox opens fine.
if I change my code to
subprocess.call(["open -a Firefox"])
I still get the error message.
You're passing open -a Firefox as one argument, as if you ran this in the shell:
$ "open -a Firefox"
You need to split up the items:
subprocess.call(['open', '-a', 'Firefox'])
Try giving the full path of firefox app.
It's wrong to use subprocess.call without shell=True or providing command as a list. Please, take a look at first examples in the docs:
http://docs.python.org/2/library/subprocess.html
Full path to Firefox may be needed or may be not needed.

Categories

Resources