多个命令到 CMD
Multiples Commands To CMD
我必须使用以下命令行工具:ncftp,
之后我需要
执行以下命令:
“打开 ftp//...”
“get -R Folder”,但我需要自动执行此操作。如何使用 Python 或命令行
实现此目的
您可以为此使用 Python subprocess
模块。
from subprocess import Popen, PIPE
# if you don't want your script to print the output of the ncftp
# commands, use Popen(['ncftp'], stdin=PIPE, stdout=PIPE)
with Popen(['ncftp'], stdin=PIPE) as proc:
proc.stdin.write(b"open ...\n") # must terminate each command with \n
proc.stdin.write(b"get -R Folder\n")
# ...etc
有关详细信息,请参阅 the documentation for subprocess
。掌握这个库的窍门可能有点棘手,但它用途广泛。
或者,您可以使用 NcFTP 包中的非交互式命令 ncftpget
(docs) and ncftpput
(docs)。
我建议在继续之前通读有关这些命令的文档。
在评论中,您说您需要获取一些文件,删除这些文件,然后上传一些新文件。方法如下:
$ ncftpget -R -DD -u username -p password ftp://server path/to/local/directory path/to/remote/directory/Folder
$ ncftpput -R -u username -p password ftp://server path/to/remote/directory path/to/local/directory/Folder
-DD
将在下载后删除所有 文件 ,但会保留目录和所有子目录
如果您需要删除空文件夹,您可以再次 运行 ncftpget
命令而无需 -R
(但文件夹必须完全为空,即没有子目录,因此根据需要冲洗并重复) .
您可以在 bash
脚本中执行此操作或在 Python 中使用 subprocess.run
。
我必须使用以下命令行工具:ncftp, 之后我需要 执行以下命令: “打开 ftp//...” “get -R Folder”,但我需要自动执行此操作。如何使用 Python 或命令行
实现此目的您可以为此使用 Python subprocess
模块。
from subprocess import Popen, PIPE
# if you don't want your script to print the output of the ncftp
# commands, use Popen(['ncftp'], stdin=PIPE, stdout=PIPE)
with Popen(['ncftp'], stdin=PIPE) as proc:
proc.stdin.write(b"open ...\n") # must terminate each command with \n
proc.stdin.write(b"get -R Folder\n")
# ...etc
有关详细信息,请参阅 the documentation for subprocess
。掌握这个库的窍门可能有点棘手,但它用途广泛。
或者,您可以使用 NcFTP 包中的非交互式命令 ncftpget
(docs) and ncftpput
(docs)。
我建议在继续之前通读有关这些命令的文档。
在评论中,您说您需要获取一些文件,删除这些文件,然后上传一些新文件。方法如下:
$ ncftpget -R -DD -u username -p password ftp://server path/to/local/directory path/to/remote/directory/Folder
$ ncftpput -R -u username -p password ftp://server path/to/remote/directory path/to/local/directory/Folder
-DD
将在下载后删除所有 文件 ,但会保留目录和所有子目录
如果您需要删除空文件夹,您可以再次 运行 ncftpget
命令而无需 -R
(但文件夹必须完全为空,即没有子目录,因此根据需要冲洗并重复) .
您可以在 bash
脚本中执行此操作或在 Python 中使用 subprocess.run
。