Python how to use shell to call the function + parameter passing in the script

[Foreword-Nonsense for myself] I
recently encountered this problem when playing python. I checked it on the Internet. Most of the blog posts talk about the same method, which seems to be half-understood, so I feel that I need to sort it out.


1. Problem description

Whether it is under windows or Linux, there are shells, powershell under windows, bash under Linux, and so on. Python under windows can have IDLE, python under Linux generally does not (this is my current knowledge, for reference only, if there is any impropriety, please feel free to enlighten me).

Sometimes, when we want to use the functions in the python script we wrote before, we don’t want to open the previous python script to modify or create a python script to call the functions in the previous python script, but we want to use the shell directly Call the function in the python script, and can pass parameters to the function, after all, most functions require parameters. This is this kind of appeal!

If it can be done (it can be done for sure, but I will not at the time of writing), then I can do a lot of things.

2. Run a python script in the shell

It is easy to run a python script in the shell, let's look at a simple python script:

#!/usr/bin/python3 
print("Hello, World!")

This example is excerpted from the rookie. Regarding the understanding of the first line, a great god wrote in the comments:

Regarding the understanding of the first line of code #!/usr/bin/python3 in the example: It is
divided into two cases:
(1) If the python script is called, the use:
python script.py#!/usr/bin/python is ignored, which is equivalent to a comment.
(2) When calling a python script, use:
./script.py#!/usr/bin/python to specify the path of the interpreter.

I am very inspired.
Now run this simple script in the shell:

  • Powershell
    Insert picture description here
    noticed the second command, it did not run the script, but opened the script with the default application (my time npp), so there is no return value, the entire interface and focus jump to npp
  • bash
    Insert picture description here

3. Call the function

This piece of reference: https://blog.csdn.net/xuezhangjun0121/article/details/91958296
I tried this, but it didn’t work: https://www.bbsmax.com/A/LPdoKwVjd3/

Follow the first link to run an example:

  • St1: Create a file port.pyand enter the following:
#!/usr/bin/python
# port.py
 
import socket
 
def scan(port):
    s = socket.socket()
    s.settimeout(0.1)
    if s.connect_ex(('localhost', port)) == 0:
        return 'port: ' + str(port) + ' open'
    else:
        return 'port: ' + str(port) + ' not open'
    s.close()
 
if __name__ == '__main__':
  scan()
  • St2: Input instructions one by one:
checkresult=`python -c 'import port; print port.scan(80)'`
echo $checkresult
python -c 'import port; print port.scan(80)'

Insert picture description here
Let me write it myself to see if it can be used to
create a file mine.pyand enter the content:

#!/usr/bin/python

def myfun(filepath,filename):
    longfilename=filepath+'/'+filename
    f=open(longfilename)
    flist=f.readlines()
    for line in flist:
        print(line)
    f.close()

if __name__ == "__main__":
    myfun()

Then create a new text file a.txtand enter the following content (enter the content casually):

Hello world!
I am Bill O'Hanlon
I am learning Python
I am very happy!
Nice to meet you!
Good bye!

Then call:

python -c 'import mine; mine.myfun(r"/home/ohanlon/Documents","a.txt")'

Insert picture description here
But it didn't work in powershell: I
Insert picture description here
don't know the reason at present, and powershell seems to be different from a normal shell. My goal has been achieved, this question will be put aside for a while, and I will talk about it later.

4. Pass parameters to the python script through the sys module

This is relatively simple, just look at an example below.

#test.py
import sys
k = float(sys.argv[1])
y = sys.argv[2]
t = int(sys.argv[3])
print(k);print(type(k))
print(y);print(type(y))
print(t);print(type(t))
------------------
python .\test.py 2.3 sfansifjdnj 4  #python3 powershell
python test.py $g $q $s   #python2 linux-bash

Insert picture description here
Insert picture description here
What if you want to store the script execution result into a shell variable?

a1=`python test.py $g $q $s`

What if you want to use multiple variables to store the results of python script execution?

a1 a2 a3=`python test.py $g $q $s`

This won't work. We can store the execution result of the python script in a1. At this time, a1 is a string:

4.76 <type 'float'> ndjknfkjs <type 'str'> 1 <type 'int'>

As you can see, it stores the content of the print above, but separates the content of each print with spaces. If it is directly converted into an array, it array=($a1)will be <type 'float'>divided into two parts because there is a space in between. In this case, we can work hard on the output: add ;, as follows:

import sys
k = float(sys.argv[1])
y = sys.argv[2]
t = int(sys.argv[3])
print(k); print(';');  print(type(k)); print(';')
print(y); print(';');  print(type(y)); print(';')
print(t); print(';');  print(type(t))

In this way, a1 becomes

4.76 ; <type 'float'> ; ndjknfkjs ; <type 'str'> ; 1 ; <type 'int'>

After to ;as the delimiter character array into:

array=(${a1//;/ })

I thought this would be fine, but it still doesn't work, because it array=(str})will split the string into an array with spaces as the delimiter by default. Then you have to change the default delimiter first and then change it back. The operation is as follows:

OLD_IFS="$IFS"
IFS=";"
array=($a1)
IFS="$OLD_IFS"
echo ${#array[@]}  #6
echo ${array[1]}   #<type 'float'>

ok!

5. Pass the variables in the shell to the python function

How can it be realized that the variables in the shell are passed to the functions in the python script? In other words, I want to use a function in the python script, but I am too lazy to separate this function from the script, but want to use it directly.
At present, there is really no good solution, and it seems that you can't be lazy.

to sum up

Python scripts scrpit.pycan generally be written as:

def function_name(param):
        return reparam
 
if __name__ == "__main__":
        function_name()  #其实这两行可以不要。

transfer:

python -c 'import script; print script.function_name(param)'

or:

result=`python -c 'import script; print script.function_name(param)'`
echo $result

The variables in the shell are passed to the python script

import sys
k = float(sys.argv[1])
y = sys.argv[2]
t = int(sys.argv[3])
-------------
python test.py $g $q $s   #调用

After the python script is executed, the result will be sent out (using print). If there are multiple variables, select a separator of your choice and add it between multiple variablesprint('分割符')

a1=`python test.py $g $q $s`
OLD_IFS="$IFS"
IFS=";"
array=($a1)
IFS="$OLD_IFS"

The final result will exist in the array as an array of characters (one index per variable).

Guess you like

Origin blog.csdn.net/Gou_Hailong/article/details/111091452