简体   繁体   English

从 python 文件运行 shell 命令

[英]Run a shell command from python file

I've seen a lot of answers for this one but im trying to run something pretty complicated.我已经看到了很多关于这个的答案,但我试图运行一些非常复杂的东西。 Trying to run something like the following command from my python file.尝试从我的 python 文件中运行类似以下命令的内容。 Some parts are missing but the basic idea is:缺少某些部分,但基本思想是:

python detect.py --source ~user/'image' --weights ~/user'ID' --img 640")

and at image and ID I've got inputs from the python file.imageID处,我从 python 文件中获得了输入。 I've tried with import.os and import.subprocess but had no luck as it seems Im messing up my file declarations probably.我已经尝试过import.osimport.subprocess但没有运气,因为我似乎弄乱了我的文件声明。

If you use subprocess.run() you want to pass in the command as a list of strings.如果您使用 subprocess.run() 您希望将命令作为字符串列表传递。 You can then use f-string formatting to put variables like with into your strings.然后,您可以使用 f 字符串格式将变量(如 with)放入您的字符串中。

import subprocess

width = 640
argument2 = f"--img {width}"

result = subprocess.run(
    ["python", "detect.py", "argument1", argument2]
)
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM