How can I use a function directly on the command line in python?

for example: my command line after running the program should be like this:

perfect(44) #using the defined function in the output screen.(44) or any other number

and the conclusion should be:

false

I tried this code, but in this I can not use funcion on the command line.


def factors(n):
    factorlist = []
    for i in range(1,n):
        if n%i == 0:
            factorlist = factorlist + [i]
    print factorlist
    return factorlist

def perfect(n): factorlist = factors(n) if sum(factorlist) == n: return True else : return False

n = int(raw_input()) print(perfect(n))

+4
source share
4 answers

Browse to the path where the file is located .py. Run the python interpreter interactively with the following command:

python -i filename.py

By doing this, you must have access to all the functions inside your file filename.py.

+4
source

You can add the following lines to your python script to call the function when the script loads.

if __name__ == '__main__':
    print(perfect(int(sys.argv[1])))

Then you can call it like this:

python myscript.py 44
+1

.

python -c "import modulename"

modulename file_name.py

0

, Google Fire.

pip install fire

:

#!/usr/bin/env python
from fire import Fire

def factors(n):
    factorlist = []
    for i in range(1,n):
        if n%i == 0:
            factorlist = factorlist + [i]
    print factorlist
    return factorlist


def perfect(n):
    factorlist = factors(n)
    if sum(factorlist) == n:
        return True
    else :
        return False

# n = int(raw_input())
# print(perfect(n))

if __name__ == '__main__':
  Fire(perfect)

Make sure your file is executable if on Mac or Linux (sorry, I don't know if it needs to be done on Windows). Assuming your code is in a file named perfect:

chmod +x perfect

If the file is in your path, you should now name it like this:

$ perfect 44
[1, 2, 4, 11, 22]
False
0
source

Source: https://habr.com/ru/post/1683294/


All Articles