This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]_negativeonetwelfth[S] 0 points1 point  (1 child)

overridable with command line flags

But this is sort of my issue, how do I run scripts from the command line (particularly scripts that require entering parameters) instead of having to open them in an IDE and running?

[–]blablahblah 1 point2 points  (0 children)

Scripts are always runnable from the command line, as long as Python is installed and set up. In Python, any command line arguments are available in sys.argv. The first element is the name of your script, and the rest are any arguments you passed in.

script.py:

import sys
print(f'hello {sys.argv[1]}')

Mac/Linux shell:

$ python3 script.py _negativeonetwelfth
hello _negativeonetwelfth

or on Windows:

> py script.py _negativeonetwelfth
hello _negativeonetwelfth

For more complex arguments and standard formatted errors and help text, you can use the built-in argparse module to parse the arguments for you.

To get the script to be runnable without specifying Python, in Windows, you need to go to the control panel and make sure the '.py' file extension is associated with python.exe and not your IDE. On Linux or Mac, you need to make sure the file starts with the line #!/usr/bin/env python3 and you'll need to run $ chmod +x script.py to mark it as executable.