gpt4 book ai didi

python - Bash + Python 中的 EoF/Ctrl+D 命令

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:44:00 24 4
gpt4 key购买 nike

我正在尝试在 python 中创建一些函数,以便我可以连接到 linux 终端并执行操作(比如在本例中,创建一个文件)。我拥有的代码部分有效。唯一不起作用的是,如果您想在输入代码后执行某些操作。例如,您创建了文件,然后想导航到其他地方 (cd/tmp)。它不会执行下一个命令,而只会添加到创建的文件中。

    def create_file(self, name, contents, location):
try:
log.info("Creating a file...")
self.device.execute("mkdir -p {}".format(location))
self.cd_path(location)
self.device.sendline("cat > {}".format(name))
self.device.sendline("{}".format(contents))
self.device.sendline("EOF") # send the CTRL + D command to save and exit I tried here with ^D as well
except:
log.info("Failed to create the file!")

文件内容为:

cat test.txt
#!/bin/bash
echo "Fail Method Requested"
exit 1
EOF
ls -d /tmp/asdasd

命令执行的顺序是:

execute.create_file(test.txt, the_message, the_location)
execute.check_path("/tmp/adsasd") #this function just checks with ls -d if the directory exists.

我已经尝试使用 sendline 以下组合: ^D, EOF, <<EOF

我真的不明白我怎么能做到这一点。我只想创建一个包含特定消息的文件。 (在研究如何使用 VI 执行此操作时,我遇到了同样的问题,但我需要的命令是用于 ESC 的命令)

如果有人能提供一些帮助,那就太好了!!

编辑:正如 Rob 在下面提到的,发送字符“\x04”确实有效。对于遇到此问题的任何其他人,如果需要,您还可以查阅此图表以了解其他组合: http://donsnotes.com/tech/charsets/ascii.html

最佳答案

您可能需要发送 EOF 字符,通常是 CONTROL-D,而不是 EOF 这三个字符.

        self.device.sendline("\x04")

关于python - Bash + Python 中的 EoF/Ctrl+D 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41447624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com