简体   繁体   中英

How to execute modules as scripts in Python

I created a module called fibo.py like the tutorial shows, which looks like this:

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n): 
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

and then I added

python fibo.py <arguments>

and I got an invalid syntax error on the f of fibo.py.

I've seen similar questions on stack overflow but none of them makes sense to me.

I've been working on this one piece of code for an hour now. Help is greatly appreciated.

You shouldn't get a syntax error. If you did, you tried to run it in an interactive console, not your system terminal. If you ran that in your system terminal, it would execute; just nothing would happen.

If this is a full module, the -m flag may be of use.

Otherwise, if this is just a standalone script, you'd need a "main" or something that achieves the same:

import sys

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()


def main():
    arg = sys.argv[1]  # Grab the arguments passed to the script
    fib(int(arg))  # Obviously, add some error handling


if __name__ == "__main__":
    main()

Then, in your terminal ( not an interactive console like iPython):

python fibo.py 100

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