[英]Execute custom command using subprocess that is in PATH variable
I want to execute another program that I compiled earlier from python using the subprocess.call(command)
function.我想执行我之前使用 subprocess.call
subprocess.call(command)
function 从 python 编译的另一个程序。
However, python states that it cannot find the command.但是,python 声明它找不到该命令。 I suspect that subprocess is not able to find my custom command since it does not know the
PATH
variable of my Ubuntu system.我怀疑子进程无法找到我的自定义命令,因为它不知道我的 Ubuntu 系统的
PATH
变量。 Is it possible to somehow execute the following code, where command is part of my PATH
?是否有可能以某种方式执行以下代码,其中 command 是我的
PATH
的一部分?
import subprocess
subprocess.run("command -args")
Running this code leads to the error command not found
.运行此代码会导致
command not found
。
You can modify the environment variables.您可以修改环境变量。 But be careful when you pass arguments.
但是当你通过 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)
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:或者在 Python 代码中修改
PATH
变量:
import os
os.environ['PATH'] += ':'+'/full/path/to/'
subprocess.run('command.sh')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.