简体   繁体   中英

Run Python script via CMD

I have the following file: up.py

in this file:

def main(a_param, b_param, c_param):
    // Code
if __name__ == '__main__':
    exit(main())

I want to run this python file via the CMD, so I write this line:

python up.py False True False

But I get the next error:

TypeError: main() takes exactly 3 arguments (0 given)

This has nothing to do with CMD. Your main function expects three arguments, but you aren't passing any; you call it directly from your if __name__ == '__main__' block with just main() .

Either get the arguments (eg from sys.argv ) within that block and pass them to main, or remove the arguments from the function signature and get them within main.

You are trying to call your main function without arguments event though it requires 3 ( a_param , b_param and c_param ).

The command line parameters are stored in sys.argv . To call the main function with the first 3 command line parameters, you could this:

import sys

if __name__ == '__main__':
    main(*sys.argv[1:4])

To clarify, * unpacks the argument list so main(*sys.argv[1:4]) is equivalent to main(sys.argv[1], sys.argv[2], sys.argv[3])

This code works for me

def main(a_param, b_param, c_param):
    # Code
    if __name__ == '__main__':
        exit(main())

then:

$ python up.py False True False

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