简体   繁体   中英

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

I have a text file say 1.txt from where I am fetching some keywords like "sent", "inbox", "outbox" etc. for it to be replaced in a command line.

Below is how the command line looks:

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

I am trying to replace the "mainlist" with the data i fetched from 1.txt file, eg

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

I have tried by adding this by creating two strings and concatenating it but looks like I am going wrong.

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)

Can someone please help me in finding solution for this i am very new to python.

It doesn't make a lot of sense to me to use Python to generate command lines that you then pass back to the shell to execute. You could use a bash script for that, that would be a lot simpler than 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

If you're doing it with Python, do it with Python. A nice library to do HTTP is called requests ( docs ).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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