首先,我将向您展示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文件然后将存储在文本文件中的命令猫化(将来,我将让它作为命令运行)。然后重新开始脚本。
问题是,当我在shell中输入"List contents"
时,它不起作用,从而打印"Didn't work"
。但是,如果我自己进入文本文件并编写"List contents"
,python脚本将工作并将"ls"
写入文本文件。我不知道为什么会发生这种事。我很乐意在这件事上提供任何帮助。
谢谢,b3n
发布于 2013-12-31 15:08:01
当您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"
https://stackoverflow.com/questions/20864037
复制