【问题标题】:how to pass a python variable into a bash script function如何将python变量传递给bash脚本函数
【发布时间】:2020-05-20 23:21:04
【问题描述】:

我已经搜索和搜索,但没有找到并回答我的特定情况,或者如果我有我不知道如何实现它。我正在尝试使用 python 和 bash 创建一个脚本来自动化我的项目创建过程。而我会使用 1 个命令行参数运行 testing.py “因为我正在测试,所以现在调用它”,这将是项目文件夹的名称,然后它会询问“我想在哪里创建项目”路径的两个选项用于存储项目并使用 if 语句将路径存储到路径变量中。然后我想在 bash 脚本中传递该变量以导航到它并在那里创建项目目录。这是我目前所拥有的:

所以我要运行的命令是这样的:

python testing.py newProject

在.test.sh中

#!/bin/bash

function testing() {
    cd 
    desktop
    python testing.py $1

}

在 testing.py 中

import sys
import os

school = "/Users/albert/Open/Microverse/"
personal = "/Users/albert/Open/code/Projects/"

path = " "

userInput = input("What type of project would you like to create? Personal or School? ")

if userInput.lower() == "personal":
    path = personal
elif userInput.lower() == "school":
    path = school


def testing():
    folderName = str(sys.argv[1])
    os.makedirs(path + str(folderName))
    print(folderName)


if __name__ == "__main__":
    testing()

【问题讨论】:

  • 这里出了什么问题?
  • 当我运行 python 脚本时,它只会在桌面上创建项目文件夹,因为那是我存储 .test.sh 和 testing.py 文件的地方,但我不知道怎么做将路径变量从 python 传递给 bash 脚本函数的正确路径。
  • 我知道路径变量正在获取正确的路径,因为当我在终端中仅使用函数中的 print(path) 运行它并打印路径变量时,它会输出正确的路径

标签: python bash automation scripting


【解决方案1】:

如下所示,使用“$1”代替$1

python testing.py "$1"

【讨论】:

    【解决方案2】:

    你必须像这样运行你的 bash 函数

    testing $1
    

    整个脚本

    #!/bin/bash
    
    function testing() {
        cd
        desktop
        python test.py $1
    }
    
    testing $1
    

    并在您的 python 部分中将input() 更改为raw_input()。 Input() 函数返回实际上将评估输入字符串并尝试将其作为 Python 代码运行。如果我尝试输入 Personal 这会给我一个错误

    What type of project would you like to create? Personal or School? Personal
    Traceback (most recent call last):
      File "test.py", line 9, in <module>
        userInput = input("What type of project would you like to create? Personal or School? ")
      File "<string>", line 1, in <module>
    NameError: name 'Personal' is not defined
    

    如果您输入personal 而不是userInput 将是/Users/albert/Open/code/Projects/ 这不是您想要的吗?

    【讨论】:

    • 您在这里假设 python 是 Python 2,但很可能 OP 实际上正在使用 Python 3 并且 input() 是完全正确的(尽管不方便;请参阅我的回答)。
    【解决方案3】:

    我猜desktop 实际上不是一个有效的命令,而你确实想要

    testing () {
        cd ~/Desktop
        python test.py "$1"
    ]
    

    不过,更好的设计可能是不要强制在桌面文件夹中创建所有项目。

    testing () {
       python ~/Desktop/test.py "$1"
    }
    

    将允许您在任何目录中运行脚本。

    更好的设计是给脚本一个适当的shebang,将其标记为可执行,将其命名为testing,并将其保存在您的PATH中;那么你根本不需要shell函数。

    恕我直言,另一种更有用的方法是允许用户在命令行中指定“个人”或“学校”,而不是强制脚本使用交互式输入。要求交互式 I/O 使脚本更难用作进一步自动化的构建块,并剥夺了用户使用 shell 历史记录和完成功能的能力。

    以下重构硬编码一个非常粗略的选项解析器,并使用dict 将项目类型映射到特定文件夹名称。

    #!/usr/bin/env python3
    
    import sys
    import os
    
    paths = {
      "school": "/Users/albert/Open/Microverse/"
      "personal": "/Users/albert/Open/code/Projects/"
    }
    
    def makeproject(type, folder):
        os.makedirs(os.path.join(path, folder))
    
    def gettype():
        while True:
            userInput = input("What type of project would you like to create? Personal or School? ")
            if userInput in paths:
                return paths[userInput]
            print("Not a valid option: {} -- try again".format(userInput))
    
    def testing():
        idx = 1
        if sys.argv[idx] == "--school":
            type = paths["school"]
            idx = 1
        elif sys.argv[idx] == "--personal":
            type = paths["personal"
            idx = 2
        else:
            type = gettype()
        folderName = sys.argv[idx]
        makeproject(type, folderName)
        print(folderName)
    
    if __name__ == "__main__":
        testing()
    

    注意sys.argv和input返回的值已经是字符串了;没有必要给他们打电话str()。

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2011-11-23
      • 2011-02-17
      相关资源
      最近更新 更多