简体   繁体   English

从shell脚本中执行python代码

[英]Execute python code from within a shell script

I want to have some python code run within a shell script. 我想在外壳程序脚本中运行一些python代码。 I don't want to rely on an external file to be ran. 我不想依靠外部文件来运行。 Is there any way to do that? 有什么办法吗?

I did a ton of googling, but there aren't any clear answers. 我做了谷歌搜索 ,但目前还没有任何明确的答案。 This code is what I find... But it relies on the external python script to be ran. 这段代码是我发现的...但是它依赖于要运行的外部python脚本。 I want it all within one file. 我希望所有内容都在一个文件中。

python python_script.py

You can use a so-called "here document": 您可以使用所谓的“此处文档”:

#!/usr/bin/env bash

echo "hello from bash"

python3 - <<'EOF'
print("hello from Python 3")
EOF

The single quotes around the first EOF prevent the usual expansions and command substitions in a shell script. 第一个EOF周围的单引号防止了Shell脚本中的常规扩展和命令替换。

If you want those to happen, simply remove them. 如果您希望这些发生,只需将其删除。

If you mean within a BASH shell script without executing any external dependencies, I am afraid you're out of luck, since BASH only interprets its own scripting language. 如果您的意思是 BASH Shell脚本中执行任何外部依赖项,那么恐怕您不走运,因为BASH仅解释其自己的脚本语言。

Your question is somewhat like asking "Can I run a Java .class file without the JVM"? 您的问题有点像询问“是否可以在没有JVM的情况下运行Java .class文件”? Obviously, you will always have the external dependency of the JRE/JVM. 显然,您将始终具有JRE / JVM的外部依赖关系。 This is the same case, you depend on the external Python compiler and interpreter. 这是相同的情况,取决于外部Python编译器和解释器。

Optionally, you have the option of including the python script inline, but it would still require the python executable. (可选)您可以选择内联包括python脚本,但是仍然需要python可执行文件。

This works: 这有效:

python -c 'print("Hi")'

Or this with BASH redirection: 或者使用BASH重定向:

python <<< 'print("Hi")'

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

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