2

I want to execute another program that I compiled earlier from python using the subprocess.call(command) function.

However, python states that it cannot find the command. I suspect that subprocess is not able to find my custom command since it does not know the PATH variable of my Ubuntu system. Is it possible to somehow execute the following code, where command is part of my PATH?

import subprocess subprocess.run("command -args") 

Running this code leads to the error command not found.

    2 Answers 2

    3

    You can either provide the explicit path to your command:

    subprocess.run('/full/path/to/command.sh') 

    or else modify your PATH variable in your Python code:

    import os os.environ['PATH'] += os.pathsep + '/full/path/to/' subprocess.run('command.sh') 
    2
    • Thanks, that worked perfectly!
      – Icetime
      CommentedNov 24, 2021 at 20:46
    • On Windows modifying the PATH from Python and then calling subprocess worked for me (Python 3.12.2 from Git Bash on Windows 11 23H2) but may not always work: the documentation mentions that [on windows] with shell=False, cwd does not override the current working directory and env cannot override the PATH environment variable. Instead the documention recommends using full path to the executable. See this answer for how to do that.CommentedDec 4, 2024 at 10:16
    1

    You can modify the environment variables. But be careful when you pass arguments.

    Try something like this:

    import os import subprocess my_env = os.environ.copy() my_env["PATH"] = "/usr/test/path:" + my_env["PATH"] subprocess.run(["command", "-args"], env=my_env) 

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.