首先,我将向您展示bash和python脚本(都在我Mac的/bin目录中):

bash脚本(esh_1):

#! /bin/bash

echo -n "Enter bash or natural-language command: "
read INPUT
echo $INPUT > ~/USER_INPUT.txt
$INPUT
if (( $? )); then echo Redirected to Python Script; esh_2; cat ~/USER_INPUT.txt; else echo Did not redirect to Python Script;  fi
esh_1


python脚本(esh_2):

#! /usr/bin/python2.7

with open('/Users/bendowling/USER_INPUT.txt', 'r') as UserInputFile:
    UserInput = UserInputFile.read()

UserInputFile = open('/Users/bendowling/USER_INPUT.txt', 'w+')

if UserInput == 'List contents':
    UserInputFile.write("ls")
else:
    print "Didn't work"

UserInputFile.close()


bash脚本接受用户的输入,将其存储在名为USER_INPUT.txt的临时文件中,然后检查其是否正常运行。如果没有,它将调用esh_2(Python脚本),该文件读取USER_INPUT.txt文件,并接受用户的输入。然后,它检查它是否等于字符串"List contents"。如果是,则将"ls"写入文本文件。然后关闭文件。然后,bash文件将存储在文本文件中的命令编入目录(以后,我将使其作为命令运行)。然后,脚本再次开始。

问题是,当我在外壳中输入"List contents"时,它不起作用,因此打印了"Didn't work"。但是,如果我自己进入文本文件并编写"List contents",则python脚本会工作并将"ls"写入文本文件。我不知道为什么会这样。我很高兴在这个问题上有任何帮助。

谢谢,
3

最佳答案

当您read()文件时,您可能会在字符串中获得换行符'\n'。尝试之一

if UserInput.strip() == 'List contents':


要么

if 'List contents' in UserInput:


另请注意,您的第二个文件open也可以使用with

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:
    if UserInput.strip() == 'List contents': # or if s in f:
        UserInputFile.write("ls")
    else:
        print "Didn't work"

关于python - 从bash脚本重定向时,将变量与字符串python比较不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20864037/

10-12 12:47
查看更多