为啥 Python 不运行我的 bash 代码?

Posted

技术标签:

【中文标题】为啥 Python 不运行我的 bash 代码?【英文标题】:Why doesn't Python run my bash code?为什么 Python 不运行我的 bash 代码? 【发布时间】:2017-05-13 03:55:51 【问题描述】:

我正在尝试调试一些为测试集成而提供的单元测试。

我确信上次我在本地机器上测试它时这有效,但这似乎已经改变 - 文件没有改变,所以我不知道从那时起发生了什么变化。

因为它是专有软件,所以我已经删除了识别 cmets 并更改了原始单元测试的一些名称。

语法错误是:

  File "unitTests.sh", line 39
    gLastFullPath=`python -c "import os; print os.path.realpath('$1')"`
                 ^
SyntaxError: invalid syntax

完整的脚本在这里:

#!/bin/bash

# If non-zero, then run in debug mode, outputting debug information
debug=0

# Set the following to 1 to force an error for testing purposes
forceError=0

separator="===================================================================================================="

#-------------------------------------------------------------------------------
# Convert the specified path to a full path and return it in the gLastFullPath
# global variable.
#
# Input params:
#   $1  - Path to convert to full
#
# Output params:
#   $gLastFullPath  -   Set to the converted full path
gLastFullPath=""
getFullPath()

    # Use Python (because it's easier than Bash) to convert the passed path to
    # a full path.
    gLastFullPath=`python -c "import os; print os.path.realpath('$1')"`


#-------------------------------------------------------------------------------
fatalError()

    echo "$separator"
    echo "Fatal Error: $1"
    echo "$separator"
    exit 1


#-------------------------------------------------------------------------------
# If a file or folder exists at the specified path, then delete it. If it's a
# directory, then its entire contents is deleted.
#-------------------------------------------------------------------------------
deleteIfExists()

    if [[ 0 -ne $debug ]]; then
        echo "deleteIfExists called..."
    fi

    if [[ -e "$1" ]]; then
        # If it's a directory, then make sure it contains no locked files
        if [[ -d "$1" ]]; then
            chflags -R nouchg "$1"
        fi

        if [[ 0 -ne $debug ]]; then
            echo "  Deleting the existing file or directory:"
            echo "    $1"
        fi

        # Do the remove and check for an error.
        /bin/rm -rf "$1"
        if [[ $? -ne 0 ]]; then
            fatalError "Unable to delete $1."
        fi
    fi

    if [[ 0 -ne $debug ]]; then
        echo
    fi



#-------------------------------------------------------------------------------
# Script starts here
#-------------------------------------------------------------------------------

# Get the full path to this script
scriptPath=`which "$0"`
getFullPath "$scriptPath"
scriptFullPath="$gLastFullPath"
scriptDir=`dirname "$scriptFullPath"`
scriptName=`basename "$scriptFullPath"`

if [[ 0 -ne $debug ]]; then
    echo "$scriptName: Debug tracing is on."
    echo
fi

# Get the SDK project root path
getFullPath "$scriptDir/.."
projRoot="$gLastFullPath"

# Get the top of the server tree
getFullPath "$projRoot/SUBSYS_TOP"
subsysTop="$gLastFullPath"

libPythonBase="$projRoot/src/lib/py/devilsoftPy"
devilsoftPython="$libPythonBase/devilsoftpy"

if [[ 0 -ne $debug ]]; then
    echo "$scriptName: Project root dir:     \"$projRoot\""
    echo "$scriptName: SUBSYS_TOP:           \"$subsysTop\""
    echo "$scriptName: Lib python base:      \"$libPythonBase\""
    echo "$scriptName: devilsoft python:    \"$devilsoftPython\""
    echo
fi

# First we have to launch the test python server. This is used by some of the other client tests to 
# run against.
testServer="$devilsoftPython/test/TestServer.py"
if [[ ! -f "$testServer" ]]; then
    fatalError "Could not find the expected test server: \"$testServer\""
fi

# Carve out a place for our test server log file
tempFolder="/tmp/devilsoft"
mkdir -p "$tempFolder"
testServerLogFile="$tempFolder/TestServer.log"

echo "Starting the test server: \"$testServer\""
echo "  Logging to this file:   \"$testServerLogFile\""
export PYTHONPATH="$libPythonBase:$PYTHONPATH"; "$testServer" > "$testServerLogFile" 2>&1 &
testServerPid=$!
echo "  Server started with pid $testServerPid..."
echo

echo "  Taking a little snooze to let the test server initialize..."
sleep 2

# If we're forcing errors for testing, then kill the test server. This will cause downstream scripts
# to fail because there will be no server to talk to.
if [[ $forceError -ne 0 ]]; then
    echo "Forcing downstream errors by killing the test server..."
    kill $testServerPid
    wait $testServerPid
    testServerPid=0
    echo
fi

testResultsLogFile="$tempFolder/TestResults.log"
echo "Testing each python script in the library..."
echo "  Test results will be written to this log file: \"$testResultsLogFile\""
echo
deleteIfExists "$testResultsLogFile"

# Save and set the field separator so that we can handle spaces in paths
SAVEIFS=$IFS
IFS=$'\n'

failedScripts=()
lastError=0
pythonSources=($(find "$devilsoftPython" -name '*.py'  ! -name '*.svn*' ! -name '__init__.py' ! -name 'TestServer.py' ! -name 'ServerClient.py'))
for pythonSourceFile in $pythonSources[*]; do
    echo "  Testing python source \"$pythonSourceFile\""
    export PYTHONPATH="$libPythonBase:$PYTHONPATH"; "$pythonSourceFile" >> "$testResultsLogFile" 2>&1
    result=$?
    if [[ $result -ne 0 ]]; then
        pythonSourceName=`basename "$pythonSourceFile"`
        echo "    Error $result returned from the above script $pythonSourceName!"
        lastError=$result
        failedScripts+=("$pythonSourceFile")
    fi
done
echo

# Restore the original field separator
IFS=$SAVEIFS

if [[ $testServerPid -ne 0 ]]; then
    echo "Telling the test server to quit..."
    kill $testServerPid
    wait $testServerPid
    echo
fi

# If we got an error, tell the user
if [[ $lastError -ne 0 ]]; then
    echo "IMPORTANT! The following scripts failed with errors:"
    for failedScript in "$failedScripts[@]"; do
       echo "  \"$failedScript\""
    done
    echo

    fatalError "Review the log files to figure out why the above scripts failed."
fi

echo "$separator"
echo " Hurray! All tests passed!"
echo "$separator"
echo

exit 0

这一切都在 Python 2.7 中运行

【问题讨论】:

这在我看来不像 Python 代码。 Python 不使用花括号来包围函数体。第一行写着#!/bin/bash。你确定这不是 bash 脚本吗? 以下是我的怀疑:OP 出现 Python 错误,因为他试图使用 Python 解释器运行此文件。当他说“我确信这在我上次在本地机器上测试它时有效”时,这是因为他上次测试它时是在 bash 中运行的。 啊,是的:碰巧它之前的所有语句也是正确的 Python!好笑。 希望 Yoda 做得更好,我做到了。 GNU coreutils 提供了命令realpath,因此您无需为此启动 Python。 【参考方案1】:

这是一个 bash 脚本,而不是 Python 脚本。使用./script_name.shbash script_name.sh 而不是python script_name.sh 运行它。

【讨论】:

所以事实证明,我是一个太累和压力太大的白痴,以至于没有注意到我试图在 Python 中运行一个 shell 脚本。感谢您的协助! ;)

以上是关于为啥 Python 不运行我的 bash 代码?的主要内容,如果未能解决你的问题,请参考以下文章

为啥这个来自 python 的 bash 调用不起作用?

为啥我的这段python代码运行不出来结果,也没报错,跪求大神指点

为啥 Git Bash 不能运行我的可执行文件?

为啥 Git Bash 不能运行我的可执行文件?

为啥在从 C# 创建的进程中运行 bash 命令时我的 $PATH 不同?

Python不会在bash中运行,但会在cmd中运行[重复]