【问题标题】:subprocess with variable for lftp [duplicate]带有lftp变量的子进程[重复]
【发布时间】:2020-10-29 12:49:55
【问题描述】:

我正在尝试从 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)

附:接近正确的答案是 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+'"'])

【问题讨论】:

  • 你能把你需要在命令行上运行的全部命令发给我吗?
  • 实际上这几乎是整个命令,但我将编辑有问题的代码。我要做的只是 ftps 服务器上的文件名每天都会不同 - 它是自动生成的,例如今天的文件名将是: 2020-10-29 - All computer.xls ,明天会有 2020-10- 30 - 所有的计算机.xls 等等

标签: python subprocess lftp


【解决方案1】:

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

当您使用 ${fname} 时,bash 将 fname 视为环境变量,您的操作系统知道该变量。由于未定义,因此将使用空值,因此找不到文件。

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

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

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

或者完全在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])

【讨论】:

  • 除非你也export fname,否则第一个命令将不起作用。更好的解决方案是在单个命令中使用fname='whatever' python your_code.py,它仅在 Python 进程期间设置fname。或者也许重构 your_code.py 以接受文件名作为命令行参数,然后您可以从 sys.argv[1] 获取。
  • 你是对的,我会编辑我的答案。
【解决方案2】:

在这里试试:

import os
import time
def python_to_bash(cli_args):
    output = os.popen(cli_args).read()    
    return output

file_name = str(time.time())+".xls"
python_to_bash("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 "+file_name)

我不知道您需要的命令是否正确,但是当我需要以这种形式使用任何动态名称时

【讨论】:

  • 我认为问题出在'-e'之后,因为假设在开头和结尾都有'"',例如它应该看起来像: (...) -e "extra命令;获取文件名”
  • 在python的开头使用简单的逗号'来bash和结束
  • 这里:python_to_bash('command here'+filename+' "other options '+dinamic_options+'"')
  • 有人关闭了我的帖子,但我已经为其他人提供了解决方案: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 some_folder;pget "+'"'+fname+'"'])
猜你喜欢
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
  • 2016-09-29
  • 2014-07-21
  • 1970-01-01
  • 2018-06-20
  • 2011-05-19
相关资源
最近更新 更多