I'm working on a script which should run a command in a new subprocess. At the moment im using the python subprocess.Popen() for this. My problem is that I can run commands like "dir" but not a installed program. When I open the cmd prompt and write "program -h" I am getting the normal help outprint. When I try to open it with Popen() I am getting an error that the program can not the found. It is like he is not finding the executable even if the cmd promt can find it when I look for it manually. For the test i used ncat as an example program.
import time
from subprocess import *
import subprocess
execom = "ncat -h" # DOES NOT WORK IN PYTHON BUT MANUALLY IN CMD
execom1 = "ncat -h -e cmd" # DOES NOT WORK IN PYTHON BUT MANUALLY IN CMD
execom2 = "dir" # WORKS
p = Popen(execom, shell=True)
out = p.communicate()[0]
Does someone know how to fix that?
EDIT: I got the solution with the hint of 2e0byo. I added the paths to the systemvariabels but the system needed an extra restart to pass it. It worked without restart from cmd prompt but not from python script. After restart it works from both now.
CodePudding user response:
Per the comments, the problem is just that ncat
isn't in your PATH, so you need to add it:
import os
env = os.environ.copy()
env["PATH"] = r"C:\Program Files (x86)\Nmap;" env["PATH"]
p = Popen(execom, env=env)
...
See this question for modifying the env.
As to why ncat isn't in your path I really don't know; I don't use Micro$oft Windoze very much. Perhaps someone will be along with a canonical answer to that question, or you can ask it over on superuser and see if someone knows how to set it up. If I needed this to be portable I would just check a bunch of folders for ncat and bail if I couldn't find it.