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

时间:2016-02-24 15:58:13

标签: python bash gcloud

从终端运行脚本:

(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

1 个答案:

答案 0 :(得分:2)

来自Python manual on os.system

的引用
  

子流程模块为生成新流程提供了更强大的功能

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

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/binenv=...,如果您愿意,也不要将其添加到您的计算机全局路径变量中。