如何在Python中链接多个命令行响应?

2024-07-02 12:58:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图在另一个python脚本中运行一个脚本,但没有成功。在

我要运行的脚本是garminbackup.py可在以下回购协议中找到。在

https://github.com/petergardfjall/garminexport

当你从命令行运行这个脚本时,它会要求你提供一些信息,用户名,保存文件的位置,等等。。。在

command = 'python garminbackup.py --backup-dir=Name email --format tcx'

然后它要求输入密码,一旦输入密码,它就开始将garmin文件下载到所提供的目录中。我的目标是创建一个程序,在多个帐户中循环并更新每个文件夹中的数据。在

我的问题是,我似乎无法让python中的子进程模块执行此操作。在

我试过下面的命令,但运气不好。它似乎卡在输入密码的屏幕上,不做任何其他事情。在

^{pr2}$

我找了好几个小时,运气不好。感谢任何帮助。在


Tags: 文件命令行pyhttpsgithub脚本com信息
1条回答
网友
1楼 · 发布于 2024-07-02 12:58:06

虽然OP通过使用 password选项解决了这个问题,但是其他人可能会偶然发现相同的问题,而且与已经出现的pointed out by HuStmpHrr一样,在命令行中传递密码不是一个好主意。在

为什么没用

被调用的脚本,在本例中garminbackup.py使用getpass。正如文档中所暗示的那样,getpass的实现比读取stdin要复杂得多:

[...] On Unix, the prompt is written to the file-like object stream. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows).

If echo free input is unavailable getpass() falls back to printing a warning message to stream and reading from sys.stdin and issuing a GetPassWarning.

它应该如何工作

我们可以模拟一个虚拟终端,但是如果没有库,那就太复杂了(见下一章)。在

另一种方法是去除存在终端的信息(“如果无回声输入不可用”)。结果比我预期的要难,通常运行命令作为cat | command | cat应该可以消除tty检测,但是getpass似乎不是聪明就是无知来改变它的行为。在

更好的方法:pexpect

mentioned by LohmarASHAR一样,如果您可以使用pexpectpip install pexpect),那么您应该。它正是为这个而设计的,将涵盖所有的角落案例。在

For example:

child = pexpect.spawn('scp foo user@example.com:.')
child.expect('Password:')
child.sendline(mypassword)

This works even for commands that ask for passwords or other input outside of the normal stdio streams. For example, ssh reads input directly from the TTY device which bypasses stdin.

要坚持OP的例子,但使用pexpect:

#!/usr/bin/env python

import pexpect

command = 'python garminbackup.py  backup-dir=Name email  format tcx'

p = pexpect.spawn(command)  # instead of subprocess.Popen
p.expect(":")               # This is waiting for the prompt "Enter password:", but I rather only use ":" to cope with internationalisation issues
p.sendline("password")
print p.read()              # Output the sub-processes output 
p.wait()

相关问题 更多 >