简体   繁体   English

如果 bash 中的某些语句为真,则执行 python 代码

[英]Executing python code if some statement is true in bash

I have the following code where if a certain condition is true i try to execute a python code inside a shell script.我有以下代码,如果某个条件为真,我尝试在 shell 脚本中执行 python 代码。 The issue is i keep getting an IndentationError: unexpected indent and i am not sure why because this indention works fine when i execute the python code outside of the if statement.问题是我不断收到IndentationError: unexpected indent ,我不知道为什么,因为当我在 if 语句之外执行 python 代码时,这个缩进工作正常。

if [ ! -z "$INSTANCE_ID" ]
then
      python -c \
      """
      from mydbmodule import db
      update_string = \
      'Update release_status SET release_deployed_at = NOW() \
      where release_deployed_at is null'

      db.execute(db.get_environment(), update_string)
      """
fi

This works:这有效:

if true; then
    python -c \
"
print ('test message')
"
fi

So does this:这样做也是如此:

if true; then
    python -c "
print ('test message')
"
fi

this raises an indentation error:这会引发缩进错误:

if true; then
    python -c \
"
    print ('test message')
"
fi

because the string Python gets is indented while it shouldn't be.因为字符串 Python 得到缩进,而它不应该缩进。

As for """ , in the shell it's pretty much the same as just one quote: """foo""" has three quoted strings, "" , "foo" , and "" . The first and third are just empty and don't do anything.至于""" ,在 shell 中,它与一个引号几乎相同: """foo"""有三个带引号的字符串, """foo""" 。第一个和第三个只是空的,并且不要做任何事情。

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

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