简体   繁体   English

从 py 脚本在虚拟环境中调用命令

[英]Calling command in virtual environment from py script

I'm very new to coding and software, so please stick with me.我对编码和软件很陌生,所以请坚持下去。 I am trying to execute a command in my Raspberry Pi terminal via a Python script.我正在尝试通过 Python 脚本在我的 Raspberry Pi 终端中执行命令。 I want to be able to run this pi script from the Desktop.我希望能够从桌面运行这个 pi 脚本。 The command to execute is (rpi-deep-pantilt-env) pi@raspberrypi:~/rpi-deep-pantilt $ rpi-deep-pantilt detect So as you can see, I need to cd into rpi-deep-pantilt, then activate my virtual environment, then run the command all via the py script.要执行的命令是(rpi-deep-pantilt-env) pi@raspberrypi:~/rpi-deep-pantilt $ rpi-deep-pantilt detect所以如你所见,我需要 cd 进入 rpi-deep-pantilt,然后激活我的虚拟环境,然后通过 py 脚本运行命令。

A simple shell script to do what you ask:一个简单的 shell 脚本来执行您的要求:

#!/bin/sh
cd "$HOME"/rpi-deep-pantilt
. ./rpi-deep-pantilt-env/bin/activate
./rpi-deep-pantilt detect "$@"

Most or all of this is probably unnecessary.大多数或所有这些可能是不必要的。 I guess you could run我猜你可以跑

#!/bin/sh
d="$HOME"/rpi-deep-pantilt
exec "$d"/rpi-deep-pantilt-env/bin/python "$d"/rpi-deep-pantilt detect "$@"

though if your Python script has hardcoded file paths which require it to run in a specific directory, that's a bug which will prevent this from working.但是,如果您的 Python 脚本具有硬编码的文件路径,需要它在特定目录中运行,那么这是一个会阻止它工作的错误。

The "$@" says to pass on any command-line arguments, so if you saved this script as pant , running pant blind mice will pass on the arguments blind and mice to your Python script. "$@"表示传递任何命令行 arguments,因此如果您将此脚本保存为pant ,运行pant blind mice会将 arguments blind鼠和mice传递给您的 ZA7F5F35426B927411FC9231B56382137 脚本。 (Of course, if it doesn't accept additional command-line arguments after detect , this is unimportant, but I'd still pass them on so you can generate an error message, rather than have them be ignored as if they were not there.) (当然,如果它在detect之后不接受额外的命令行 arguments ,这并不重要,但我仍然会将它们传递给您,这样您就可以生成错误消息,而不是让它们被忽略,就好像它们不存在一样.)

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

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