如何在 Bash 脚本中导入 Python 文件?(在 Bash 脚本中使用 Python 值)

3 投票
3 回答
6697 浏览
提问于 2025-04-18 13:32

我想知道在一个bash脚本中是否可以包含一个python脚本,以便在bash脚本中写入我在python程序中写的一个函数的返回值?

举个例子:我的文件“file.py”里有一个函数,它返回一个变量值“my_value”(这个值代表一个文件的名字,反正就是这样)。我想创建一个bash脚本,能够执行类似“ingest my_value”的命令行。

所以你知道怎么在bash脚本中包含一个python文件(比如用import...?)吗?还有怎么在bash脚本里调用python文件中的一个值?

谢谢你提前的帮助。

更新

其实,我的python文件是这样的:

class formEvents():
    def __init__(self):
        ...
    def myFunc1(self): # function which returns the name of a file that the user choose in his computeur
    ...
    return name_file        

    def myFunc2(self): # function which calls an existing bash script (bash_file.sh) in writing the name_file inside it (in the middle of a line)
        subprocess.call(['./bash_file.sh'])

if__name__="__main__":
    FE=formEvents()

我不知道这是否足够清楚,但我的问题是:我想在bash_file.sh里写入name_file。

Jordane

3 个回答

0

另外,你可以让这个bash脚本处理一些参数。

#!/usr/bin/bash

if [[ -n "$1" ]]; then
     name_file="$1"
else
    echo "No filename specified" >&2
    exit 1
fi
# And use $name_file in your script

在Python中,你的子进程调用也应该相应地进行调整:

subprocess.call(['./bash_file.sh', name_file])
0

如果你的Python脚本把返回值输出到控制台,你只需要这样做

my_value=$(command)

补充:真是的,居然被你抢先了

4

最简单的方法就是通过标准的 UNIX 管道 和你的命令行工具来实现。

下面是一个例子:

foo.sh:

#!/bin/bash

my_value=$(python file.py)
echo $my_value

file.py:

#!/usr/bin/env python

def my_function():
    return "my_value"

if __name__ == "__main__":
    print(my_function())

这个过程很简单:

  1. 你先运行 foo.sh
  2. 然后 Bash 会启动一个子进程,运行 python file.py
  3. Python(还有对 file.py 的解释)会执行 my_function 这个函数,并把返回的结果输出到“标准输出”
  4. Bash 会把 Python 进程的“标准输出”捕获到 my_value 这个变量里
  5. 最后,Bash 只需把 my_value 里的值再输出到“标准输出”,你就能在命令行/终端看到“my_value”的值被打印出来。

撰写回答