繁体   English   中英

Python 2.7 - 仅替换整个命令行的一部分的优化方法

[英]Python 2.7 - optimised way to replace only a part of entire command line

我有一个文本文件,比如1.txt ,我从中获取一些关键字,如“已发送”、“收件箱”、“发件箱”等,以便在命令行中替换它。

下面是命令行的外观:

curl -H "pqr: thisisalsolink" -X PUT "https://example.com/artifactory/xyz/mainlist/oldtext.txt" -T newtext.txt

我正在尝试用我从1.txt文件中获取的数据替换“主列表”,例如

curl -H "pqr: thisisalsolink" -X PUT "https://example.com/artifactory/xyz/sent/oldtext.txt" -T newtext.txt
curl -H "pqr: thisisalsolink" -X PUT "https://example.com/artifactory/xyz/inbox/oldtext.txt" -T newtext.txt

我尝试通过创建两个字符串并连接它来添加它,但看起来我错了。

ltppath=r"/home/Desktop/1.txt"
with open((ltppath),'r') as fh:
    ls=fh.readlines()
    for line in ls:
        string1="curl -H "pqr: thisisalsolink" -X PUT "https://example.com/artifactory/xyz/"+line.strip()
        string2="/oldtext.txt" -T newtext.txt"
        conc=string1+string2
        cmd=os.system(conc)

有人可以帮我找到解决方案吗?我对 python 很陌生。

对我来说,使用 Python 生成命令行,然后将其传回 shell 执行,这没有多大意义。 您可以为此使用 bash 脚本,这将比 Python 简单得多:

while read line; do
  curl -H "pqr: thisisalsolink" -X PUT "https://example.com/artifactory/xyz/$line/oldtext.txt" -T newtext.txt
done </home/Desktop/1.txt

如果您使用 Python 执行此操作,请使用 Python 执行此操作。 一个很好的库来做 HTTP 被称为requests文档)。

import requests

upload_headers = {
    'pqr': 'thisisalsolink'
}

with open('/home/Desktop/1.txt', 'r') as fh:
    for line in fh:
        url = 'https://example.com/artifactory/xyz/' + line.strip() + '/oldtext.txt'
        with open('/home/Desktop/newtext.txt') as new_txt:
            requests.put(url, headers=upload_headers, data=new_txt)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM