首页 > 解决方案 > 带有 lftp 变量的子进程

问题描述

我正在尝试从 python 脚本调用子进程。脚本将在 linux 上使用特定参数调用“lftp”,如下所示。我无法传递文件名的问题(文件名每天都会不同)。

我尝试了几乎所有组合,但都没有成功(例如:${fname}、、$fname等等{fname})。我的想法不多了,所以我正在寻求帮助。

每次我得到来自 ftps 服务器的响应Access failed: 550 The system cannot find the file specified。我可以正确登录并更改文件夹。

import subprocess
import datetime


fname=different_every_day

proc=subprocess.call(
    ["lftp", "-u", "user:password", "ftps://servername:990", "-e",
     "set ftp:ssl-protect-data true; set ftp:ssl-force true; "
     "set ssl:verify-certificate no;get ${fname}"])

print(proc)

PS接近正确答案是wagnifico,所以我会接受他的答案,但对于其他需要解决方案的人来说,假设如下:

proc=subprocess.call(["lftp","-u","user:pass","ftps://example.something","-e","set ftp:ssl-protect-data true; set ftp:ssl-force true; set ssl:verify-certificate no;cd Ewidencja;pget "+'"'+fname+'"'])

标签: pythonsubprocesslftp

解决方案


您正在混合 python 和环境变量。

当您使用 时${fname},bash 会考虑fname一个环境变量,这是您的操作系统已知的。由于未定义,它将使用空值,因此找不到文件。

您要么需要fname在终端中定义,然后他们在 python 中调用它,如问题所示:

export fname='2020-10-29 - All computers.xls'
python your_code.py

此外,您需要在shell=True调用 subprocess.call 时添加标志

或者完全在 python 中定义它:

fname='2020-10-29 - All computers.xls'
proc=subprocess.call(
    ["lftp", "-u", "user:password", "ftps://servername:990", "-e",
     "set ftp:ssl-protect-data true; set ftp:ssl-force true; "
     "set ssl:verify-certificate no;get " + fname])

推荐阅读