简体   繁体   中英

how to pass a python variable into a bash script function

I have searched and searched and searched but have not found and answer to my particular situation, or if I had I don't know how to implement it. I'm trying to create a script using python and bash to automate my project creation process. Whereas I would run the testing.py "as it is called now because I'm testing" with 1 command line argument which would be the name of the project folder, then it would ask "where I would like to create the project" with two options for paths to store the project and store the path using an if statement into the path variable. then I would like to pass that variable in the bash script to navigate to it and create the project directory there. here is what I have so far:

so the command that I would run is like:

python testing.py newProject

in the .test.sh

#!/bin/bash

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

}

and in the 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()

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

python testing.py "$1"

You have to run your bash function like this

testing $1

The whole script

#!/bin/bash

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

testing $1

And change input() to raw_input() in your python part. Input() function returns will actually evaluate the input string and try to run it as Python code. And if i try to input Personal this give me an error

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

And if you input personal than userInput will be /Users/albert/Open/code/Projects/ wich is not wat you want right?

I'm guessing desktop is not actually a valid command, and that you really want

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

A better design might be to not force all projects to be created inside your desktop folder, though.

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

will let you run the script in any directory.

A still better design would be to give the script a proper shebang, mark it executable, call it testing , and save it in your PATH ; then you don't need a shell function at all.

A different and IMHO more usable approach would be to allow the user to specify "personal" or "school" as part of the command line, instead of forcing the script to use interactive input. Requiring interactive I/O makes the script harder to use as a building block in further automation, and robs the user of the ability to use the shell's history and completion features.

The following refactoring hard-codes a very crude option parser, and uses a dict to map the project type to a specific folder name.

#!/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()

Notice that sys.argv and the value returned by input are already strings; there is no need to call str() on them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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