简体   繁体   English

Bash 在 shell 脚本中内联运行 python 仍然无法正常工作

[英]Bash running python inline in shell script still not working

I am on Windows and using GitBash to run shell scripts in bash that run python scripts.我在 Windows 上并使用 GitBash 在 bash 中运行 shell 脚本,这些脚本运行 Z23EEEB4347BDD26BDDFCB7EE。

I'm trying to run python inline in a bash shell script using the answer from How to execute Python inline from a bash shell . I'm trying to run python inline in a bash shell script using the answer from How to execute Python inline from a bash shell .

I'm using a specific python environment, and the path is defined with an alias.我使用的是特定的 python 环境,路径是用别名定义的。

This is a file called .pyalias :这是一个名为.pyalias的文件:

alias mypython='C:/users/name/mypath/python.exe test.sh'

This is a file called test.sh :这是一个名为test.sh的文件:

# misc notes at top, like a docstring
print("Hello")
# real file will instead say myPyScript.py etc.

Here is the problem: This is a file called main_run_all.sh :这是问题所在:这是一个名为main_run_all.sh的文件:

# misc notes at top, like a docstring

shopt -s expand_aliases
source ./.pyalias

mypython test.sh

mypython -c print("Hello Again")

When I run sh main_run_all.sh , it prints "Hello" to the console (good, it is successfully running the test.sh script), but then it doesn't run the inline command, returning the following error:当我运行sh main_run_all.sh时,它会在控制台打印“Hello”(很好,它正在成功运行test.sh脚本),但随后它不运行内联命令,返回以下错误:

test.sh: line 8: syntax error near unexpected token `('
test.sh: line 8: `mypython -c print("Hello Again")'

You need to put the python code in quotes so the shell doesn't try to parse it like shell code:您需要将 python 代码放在引号中,这样 shell 就不会像 shell 代码那样尝试解析它:

mypython -c 'print("Hello Again")' 
# ..........^....................^

If you get python code that contains both double and single quotes, quoting can be a real pain.如果你得到包含双引号和单引号的 python 代码,那么引用可能会很痛苦。 That's the point when you use a quoted here-doc:这就是您使用引用的 here-doc 时的重点:

python <<'END_PYTHON'
print("Hello")
print('World')
END_PYTHON

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

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