First I'll show you both the bash and python script (both are in the /bin
directory on my mac):
The bash script (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
The python script (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()
The bash script takes the user's input, stores it in a temporary file called USER_INPUT.txt
, and checks if it runs correctly. If it doesn't, it calls esh_2
(the python script) which reads the USER_INPUT.txt
file, taking the user's input. It then checks if it's equal to the string "List contents"
. If it is, then it writes "ls"
to the text file. It then closes the file. The bash file then cats the command stored in the text file (in the future I will make it run it as a command). The script then starts again.
The problem is that when I enter "List contents"
into the shell, it doesn't work, thus printing "Didn't work"
. However, if I go into the text file myself and write "List contents"
, the python script works and writes "ls"
to the text file. I have no clue why this is happening. I would gladly appreciate any help on this matter.
Thanks, b3n
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use 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"
Source: Stackoverflow.com