Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any way to use absolute path in python subprocess check_output

Tags:

python

new to python, i found that subprocess's check_output runs nicely on Windows but it seems to only run cmds that are in windows PATH env variable.

i can execute the following fine:

import sys
from subprocess import check_output

cmd = check_output("ipconfig", shell=True)
print(cmd.decode(sys.stdout.encoding))

and ipconfig output is displayed fine.

if i try run a specific command not in the path and try absolute path i get errors.

import sys
from subprocess import check_output

cmd = check_output("c:\\test\\test.exe", shell=True)
print(cmd.decode(sys.stdout.encoding))

Is there no way to use an absolute path reference for check_output? i was not finding any..

i even tried changing to that directory..

import sys
from subprocess import check_output
import os

os.chdir("c:\\test\\")
cmd = check_output("test.exe", shell=True)
print(cmd.decode(sys.stdout.encoding))

but i get the following error

File "C:\Python35\lib\subprocess.py", line 398, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'naviseccli.exe' returned non-zero exit status 1

Process finished with exit code 1
like image 502
john johnson Avatar asked Oct 17 '22 13:10

john johnson


2 Answers

Popen offers a 'cwd' argument, that will execute in the defined directory:

import subprocess
cmd = subprocess.Popen('test.exe', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd='C:/test', shell=True)

out, err = cmd.communicate()
print (out)

Using check_output:

subprocess.check_output('cd C:/windows && notepad.exe', shell=True)
like image 157
Maurice Meyer Avatar answered Oct 21 '22 05:10

Maurice Meyer


Please read about the documentation of CalledProcessError.

You can examine the output by catching this exception in a try ... except block and using the exception instance's output attribute.

try:
    ... ...                       # Running the command.
except CalledProcessError as cmderr:
    print (cmderr.output)         # Example of using the output.

In this way you can examine the failed command's exit status and output. I don't know what triggered the exact error, but it's unlikely a result of using the absolute path.

like image 27
Cong Ma Avatar answered Oct 21 '22 04:10

Cong Ma