Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

bash - Get a string in Shell/Python using sys.argv

I'm beginning with bash and I'm executing a script :

$ ./readtext.sh ./InputFiles/applications.txt 

Here is my readtext.sh code :

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

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

I want to print the string ("./InputFiles/applications.txt") in a python file, I used sys.argv[1] but this line gives me -c. How can I get this string ? Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is easier for you to pass the parameter "$1" to the internal command python3.

If you don't want to do that, you can still get the external command line parameter with the trick of /proc, for example:

$ cat parent.sh 
#!/usr/bin/bash

python3 child.py
$ cat child.py
import os

ext = os.popen("cat /proc/" + str(os.getppid()) + "/cmdline").read()
print(ext.split('')[2:-1])
$ ./parent.sh aaaa bbbb
['aaaa', 'bbbb']

Note:

  1. the shebang line in parent.sh is important, or you should execute ./parent.sh with bash, else you will get no command line param in ps or /proc/$PPID/cmdline.
  2. For the reason of [2:-1]: ext.split('') = ['bash', './parent.sh', 'aaaa', 'bbbb', ''], real parameter of ./parent.sh begins at 2, ends at -1.

Update: Thanks to the command of @cdarke that "/proc is not portable", I am not sure if this way of getting command line works more portable:

$ cat child.py
import os

ext = os.popen("ps " + str(os.getppid()) + " | awk ' { out = ""; for(i = 6; i <= NF; i++) out = out$i" " } END { print out } ' ").read()
print(ext.split(" ")[1 : -1])

which still have the same output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...