简体   繁体   English

从bash脚本重定向时,将变量与字符串python比较不起作用

[英]Comparing a variable with a string python not working when redirecting from bash script

First I'll show you both the bash and python script (both are in the /bin directory on my mac): 首先,我将向您展示bash和python脚本(都在我的Mac的/bin目录中):

The bash script ( esh_1 ): 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

The python script ( esh_2 ): 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()

The bash script takes the user's input, stores it in a temporary file called USER_INPUT.txt , and checks if it runs correctly. bash脚本接收用户的输入,将其存储在名为USER_INPUT.txt的临时文件中,然后检查其是否正常运行。 If it doesn't, it calls esh_2 (the python script) which reads the USER_INPUT.txt file, taking the user's input. 如果没有,它将调用esh_2 (Python脚本),该文件将读取USER_INPUT.txt文件,并接受用户的输入。 It then checks if it's equal to the string "List contents" . 然后,它检查它是否等于字符串"List contents" If it is, then it writes "ls" to the text file. 如果是,则将"ls"写入文本文件。 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). 然后,bash文件将存储在文本文件中的命令编入目录(以后,我将使其作为命令运行)。 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" . 问题是,当我在外壳中输入"List contents" ,它不起作用,因此打印了"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. 但是,如果我自己进入文本文件并编写"List contents" ,则python脚本将工作并将"ls"写入文本文件。 I have no clue why this is happening. 我不知道为什么会这样。 I would gladly appreciate any help on this matter. 我很高兴在这个问题上有任何帮助。

Thanks, b3n 谢谢,b3n

When you read() the file, you may get a newline character '\\n' in your string. 当您read()文件时,您的字符串中可能会得到换行符'\\n' Try either 尝试之一

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

or 要么

if 'List contents' in UserInput:

Also note that your second file open could also use with : 还要注意的是你的第二个文件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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM