簡體   English   中英

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

[英]EoF / Ctrl+D command in Bash + Python

我試圖在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")

http://wiki.bash-hackers.org/syntax/redirection#here_documents

在此文檔中,您可以使用任何您想代表文件結尾的文件輸入終止字符串(例如您現在嘗試使用的文字EOF)。 引用該字符串告訴外殼程序不要解釋heredoc內容內的擴展,確保將所述內容視為文字。

在此處使用pipes.quote()可確保帶有文字引號, $ s,空格或其他令人驚訝的字符的文件名不會破壞您的腳本。 (當然,您需要import pipes ;相比之下,在Python 3上,它已移至shlex.quote() )。

self.device.sendline("cat > {} <<'EOF'".format(pipes.quote(name)))

然后,您可以告訴bash將其解釋為文件輸入的結尾,從而按原樣編寫EOF。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM