Get a string in Shell/Python with subprocess

2019-06-14 15:22发布

问题:

After this topic Get a string in Shell/Python using sys.argv , I need to change my code, I need to use a subprocess in a main.py with this function :

def download_several_apps(self):
     subproc_two = subprocess.Popen(["./readtext.sh", self.inputFileName_download], stdout=subprocess.PIPE)

Here is my file readtext.sh

#!/bin/bash    
filename="$1"
counter=1
while IFS=: true; do
  line=''
  read -r line
  if [ -z "$line" ]; then
    break
  fi

  python3 ./download.py \
    -c ./credentials.json \
    --blobs \
    "$line"
done < "$filename"

And my download.py file

if (len(sys.argv) == 2):
    downloaded_apk_default_location = 'Downloads/'

else:
    readtextarg = os.popen("ps " + str(os.getppid()) + " | awk ' { out = \"\"; for(i = 6; i <= NF; i++) out = out$i\" \" } END { print out } ' ").read()
    textarg = readtextarg.split(" ")[1 : -1][0]
    downloaded_apk_default_location = 'Downloads/'+textarg[1:]

How can I get and print self.inputFileName_download in my download.py file ? I used sys.argv as answerd by @tripleee in my previous post but it doesn't work as I need.

回答1:

Ok I changed the last line by :

downloaded_apk_default_location = 'Downloads/'+textarg.split("/")[-1]

to get the textfile name



回答2:

The shell indirection seems completely superfluous here.

import download

with open(self.inputFileName_download) as apks:
    for line in apks:
        if line == '\n':
            break
        blob = line.rstrip('\n')
        download.something(blob=blob, credentials='./credentials.json')

... where obviously I had to speculate about what the relevant function from downloads.py might be called.