gpt4 book ai didi

python - 由于缺少程序,从 python 运行 bash 脚本失败

转载 作者:行者123 更新时间:2023-12-01 04:05:54 24 4
gpt4 key购买 nike

从终端运行脚本:

(my_venv) ➜  my_directory bash ../../Framework/deploy_scripts/my_script.sh production
env is production
username on localhost is my_user
user in remote server is jenkins
copying everything by jenkins User from jenkins01
working....

现在我尝试通过同一目录中的python来执行此操作

os.system('bash ../../Framework/deploy_scripts/my_script.sh ' + env)
getting
env is production
username on localhost is my_user
user in remote server is jenkins
copying everything by jenkins User from jenkins01
/scripts_directory/utility_functions.sh: line 92: gcloud: command not found

gcloud是我使用的一个程序。不明白为什么没有定义 gcloud

编辑:尝试过

which gcloud                                                                          
/Users/my_user/google-cloud-sdk/bin/gcloud

再次,当我直接从 python 运行它时它可以工作 - 不工作。

所以这两行:

/Users/my_user/google-cloud-sdk/bin/gcloud compute copy-files --zone "$ZONE" "$USER@$SERVER_NAME":"$REMOTE_DIR_LOCATION" "$LOCAL_DIR_LOCATION"

 gcloud compute copy-files --zone "$ZONE" "$USER@$SERVER_NAME":"$REMOTE_DIR_LOCATION" "$LOCAL_DIR_LOCATION"

不适合我。

/Users/my_user/google-cloud-sdk/bin/gcloud 的错误不同

 File "/Users/my_user/google-cloud-sdk/./lib/third_party/argparse/__init__.py", line 85, in <module>
import copy as _copy
ImportError: No module named copy

最佳答案

引自 Python manual on os.system :

The subprocess module provides more powerful facilities for spawning new processes

以下是有关如何转换脚本的示例:

import shlex, os
from subprocess import Popen, PIPE, STDOUT

cmd = '/Users/my_user/google-cloud-sdk/bin/gcloud'
params = 'compute copy-files --zone "$ZONE" "$USER@$SERVER_NAME":"$REMOTE_DIR_LOCATION" "$LOCAL_DIR_LOCATION"'
proc = Popen([cmd] + shlex.split(params), shell=False, stdout=PIPE, stderr=STDOUT, env=os.environ())

while proc.poll() is None: # If it's None, it means it haven't finished running.
print(proc.stdout.read()) # while process is running, output anything it gives.

proc.stdout.close() # Never forget to close your open filehandles!

env=os.environ() 是您可以添加运行脚本所需的其他路径的位置。您甚至可以仅针对此脚本将 /Users/my_user/google-cloud-sdk/bin 添加到 env=... 中,而不将其添加到您的计算机全局路径变量中,如果你愿意的话。

关于python - 由于缺少程序,从 python 运行 bash 脚本失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35606899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com