gpt4 book ai didi

python - 如何使用 Pexpect 执行 root 命令?

转载 作者:可可西里 更新时间:2023-11-01 11:48:39 25 4
gpt4 key购买 nike

我正在开发一个 python 程序来协助 apt-get 工具。我想使用 pexpect 下载所选的包。我相信我陷入了 child.expect 行。到那条线好像超时了。

butt = "vlc"
child = pexpect.spawn('sudo apt-get install ' + butt)
child.logfile = sys.stdout
child.expect('[sudo] password for user1: ')
child.sendline('mypassword')

这是日志文件。

TIMEOUT: Timeout exceeded.
<pexpect.spawn object at 0xb5ec558c>
version: 3.2
command: /usr/bin/sudo
args: ['/usr/bin/sudo', 'apt-get', 'install', 'vlc']
searcher: <pexpect.searcher_re object at 0xb565710c>
buffer (last 100 chars): '[sudo] password for user1: '
before (last 100 chars): '[sudo] password for user1: '
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 27641
child_fd: 4
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: <open file '<stdout>', mode 'w' at 0xb74d8078>
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1

更新:

密码发送得很好。它还期待下一行,但随后输入“Y”并且什么都不做。

child = pexpect.spawn('sudo apt-get install ' + butt)
child.logfile = sys.stdout
child.expect_exact('[sudo] password for user1: ')
child.sendline('mypass')
child.expect_exact('Do you want to continue? [Y/n] ')
child.sendline('Y')

已解决:

我需要在末尾添加这一行。

child.expect(pexpect.EOF, timeout=None)

最佳答案

试试 child.expect_exact()

来自文档:

The expect() method waits for the child application to return a given string. The string you specify is a regular expression, so you can match complicated patterns.

只有在需要匹配正则表达式时才使用 expect() 是一种很好的做法。

关于python - 如何使用 Pexpect 执行 root 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907546/

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