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

2024-10-01 13:43:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如: 我的档案”文件.py“有一个函数,该函数返回一个变量值“my_value”(它表示文件名,但无论如何) 我想创建一个bash脚本,它必须能够执行命令行,比如“摄取我的值”

那么你知道如何在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中写入name_文件_文件.sh在

乔丹


Tags: 文件ofthe函数nameinself脚本
3条回答

或者,您可以使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中,应相应地更改子进程调用:

^{pr2}$

如果python脚本将返回值输出到控制台,您应该能够这样做

my_value=$(command)

编辑:见鬼,快来吧

最简单的方法是通过标准的UNIX Pipeline和您的Shell。在

下面是一个例子:

福斯:

#!/bin/bash

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

文件.py:

^{pr2}$

其工作原理很简单:

  1. 启动foo.sh
  2. Bash生成一个子进程并运行python file.py
  3. Python(file.py的解释)运行函数my_function,并将其返回值打印到“标准输出”
  4. Bash在my_value中捕获Python进程的“标准输出”
  5. Bash然后简单地将存储在my_value中的值回显到“标准输出”,您应该会看到“myu value”打印到Shell/终端。在

相关问题 更多 >