gh-114241: Fix and improve the ftplib CLI (GH-114242)

* Fix writing the retrieved binary file to stdout.
* Add a newline after writing warnings to stderr.
* Fix a TypeError if the netrc file doesn't contain a host/default entry.
* Improve the usage message.
This commit is contained in:
Serhiy Storchaka 2024-01-21 22:16:45 +02:00 committed by GitHub
parent 336030161a
commit 42d72b23dd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 17 additions and 10 deletions

View File

@ -900,11 +900,17 @@ def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
def test(): def test():
'''Test program. '''Test program.
Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ... Usage: ftplib [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
-d dir Options:
-l list -d increase debugging level
-p password -r[file] set alternate ~/.netrc file
Commands:
-l[dir] list directory
-d[dir] change the current directory
-p toggle passive and active mode
file retrieve the file and write it to stdout
''' '''
if len(sys.argv) < 2: if len(sys.argv) < 2:
@ -930,15 +936,14 @@ def test():
netrcobj = netrc.netrc(rcfile) netrcobj = netrc.netrc(rcfile)
except OSError: except OSError:
if rcfile is not None: if rcfile is not None:
sys.stderr.write("Could not open account file" print("Could not open account file -- using anonymous login.",
" -- using anonymous login.") file=sys.stderr)
else: else:
try: try:
userid, acct, passwd = netrcobj.authenticators(host) userid, acct, passwd = netrcobj.authenticators(host)
except KeyError: except (KeyError, TypeError):
# no account for host # no account for host
sys.stderr.write( print("No account -- using anonymous login.", file=sys.stderr)
"No account -- using anonymous login.")
ftp.login(userid, passwd, acct) ftp.login(userid, passwd, acct)
for file in sys.argv[2:]: for file in sys.argv[2:]:
if file[:2] == '-l': if file[:2] == '-l':
@ -951,7 +956,9 @@ def test():
ftp.set_pasv(not ftp.passiveserver) ftp.set_pasv(not ftp.passiveserver)
else: else:
ftp.retrbinary('RETR ' + file, \ ftp.retrbinary('RETR ' + file, \
sys.stdout.write, 1024) sys.stdout.buffer.write, 1024)
sys.stdout.buffer.flush()
sys.stdout.flush()
ftp.quit() ftp.quit()