如何用subprocess.Popen执行带有很多入参的python脚本,并得到它的PID?其中入参为/opt/hikvision/web/components/tomcat85linux64.1/ /opt/hikvision/web/components/xconfig.1/bin/xconfig-server/config /opt/hikvision/web/components/sac.1/bin/web /opt/hikvision/web/components/activemq514linux64.1/bin/linux-x86-64 /opt/hikvision/web/components/rabbitmq.1/bin/rabbitmq-auth/config /opt/hikvision/web/components/ls.1/script/license /opt/hikvision/web/components/xresmgr.1/bin/xresmgr-rms/config /opt/hikvision/web/components/loganalysis.1/bin/loges /opt/hikvision/web/components/xjob.1/bin/xjob-server/config /opt/hikvision/web/components/xdictionary.1/bin/xdictionary-dds/config
时间: 2023-07-06 14:38:11 浏览: 170
可以使用 `subprocess.Popen` 来执行带有很多入参的 Python 脚本,并得到它的 PID。下面是一个例子:
```python
import subprocess
# 定义命令行参数
args = ["python", "script.py", "/opt/hikvision/web/components/tomcat85linux64.1/", "/opt/hikvision/web/components/xconfig.1/bin/xconfig-server/config", "/opt/hikvision/web/components/sac.1/bin/web", "/opt/hikvision/web/components/activemq514linux64.1/bin/linux-x86-64", "/opt/hikvision/web/components/rabbitmq.1/bin/rabbitmq-auth/config", "/opt/hikvision/web/components/ls.1/script/license", "/opt/hikvision/web/components/xresmgr.1/bin/xresmgr-rms/config", "/opt/hikvision/web/components/loganalysis.1/bin/loges", "/opt/hikvision/web/components/xjob.1/bin/xjob-server/config", "/opt/hikvision/web/components/xdictionary.1/bin/xdictionary-dds/config"]
# 执行脚本
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 获取进程 ID
pid = process.pid
# 打印进程 ID
print("PID:", pid)
# 获取输出
output, error = process.communicate()
# 打印输出和错误
print(output.decode())
print(error.decode())
```
上述代码中,`args` 变量定义了要执行的命令和参数。在这个例子中,我们要执行 `script.py` 脚本,并传入多个命令行参数,每个参数都是一个路径。
然后,我们使用 `subprocess.Popen` 来执行这个命令。`stdout=subprocess.PIPE` 和 `stderr=subprocess.PIPE` 参数表示要把标准输出和标准错误输出都保存下来,以便后面使用。
接着,我们使用 `process.pid` 属性来获取进程的 PID,并将其保存在变量 `pid` 中。
最后,我们打印进程的 PID,获取脚本的输出和错误信息,并通过 `decode()` 方法将字节字符串转换为文本字符串。最后,我们打印输出和错误信息。
阅读全文