bash 中的 Python 命令找不到 -c 标志

bash 中的 Python 命令找不到 -c 标志

我的 bash 脚本中有两行 python 代码,它们都应该运行-C标志,但一旦我运行 Bash 脚本,它就会告诉我找不到-Cpython 在 Bash 中运行命令所需的标志。它确实从命令中工作,就像如果我将 python 命令复制到命令行它会运行该命令,但不是从脚本内部运行。

错误输出:

mount.sh: 40: mount.sh: -c: not found

我的脚本:

## define a function that launched the zenity username dialog
get_username(){
    zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Username:"
}
# define a function that launched the zenity password dialog
get_password(){
    zenity --entry --width=300 --title="Mount $MOUNTDIR" --text="Password:" --hide-text
}

# attempt to get the username and exit if cancel was pressed.
wUsername=$(get_username) || exit

# if the username is empty or matches only whitespace.
while [ "$(expr match "$wUsername" '.')" -lt "1" ]; do
    zenity --error --title="Error in username!" --text="Please check your username! Username field can not be empty!"  || exit
    wUsername=$(get_username) || exit
done

wPassword=$(get_password) || exit

while [ "$(expr match "$wPassword" '.')" -lt "1" ]; do
    zenity --error --title="Error in password!" --text="Please check your password! Password field can not be empty!" || exit
    wPassword=$(get_password) || exit
done

python -c 'import keyring; keyring.set_password("WinMount", wUsername, wPassword)'

Get_wPassword=python -c 'import keyring; keyring.get_password("WinMount", wUsername)'

# mount windows share to mountpoint
sudo mount -t cifs //$SERVER/$SHARE ${HOME}/${DIRNAME} -o username=${wUsername},password=$Get_wPassword,domain=${DOMAIN}

答案1

Get_wPassword=python -c 'import keyring; keyring.get_password("WinMount", wUsername)'

应该可能是

Get_wPassword=$(python -c 'import keyring; keyring.get_password("WinMount", wUsername)')

如果你想wUsername通过 shell 变量赋予相同的名称

Get_wPassword=$(python -c "import keyring; keyring.get_password('WinMount', '$wUsername')")

(请注意双引号如何变为单引号,反之亦然)

答案2

这是因为那一行:

Get_wPassword=python -c 'import keyring; keyring.get_password("WinMount", wUsername)'

-c被解释为命令。写法如下:

Get_wPassword=$(python -c 'import keyring; keyring.get_password("WinMount", wUsername)')

编辑:对于 bash 变量的问题。您可以使用os.getenv以下方法从 Python 访问环境变量:

export wUsername
export wPassword
Get_wPassword=$(python -c "import keyring; import os; \
keyring.get_password("WinMount", os.getenv('wUsername'))")
unset wPassword

答案3

线路

Get_wPassword=python -c 'import keyring; keyring.get_password("WinMount", wUsername)'

表示“将-c$Get_wPassword 设置为python

要设置$Get_wPassword整个命令,请使用

Get_wPassword='python -c \'import keyring; keyring.get_password("WinMount", wUsername)\''

相关内容