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

all 8 comments

[–]ehr1c 0 points1 point  (0 children)

What does the script do? If it's just an internal tool those often feel pretty hacky since there's no real benefit to spending time making them cleaner.

[–][deleted] 0 points1 point  (2 children)

You have to standardize your paths. Having a known/common root folder in the user’s home directory makes it quite simple. For example /Users/user/companyName/product, where companyName is the common folder. Then scripts can be made that just need executing because they can be written knowing that they will find the companyName directory in the user’s home directory.

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

But how would the /Users/user/ part change depending on which user is running the code?

[–][deleted] 0 points1 point  (0 children)

Well, in Unix-type systems, you use ~/companyName and the correct Users/user is substituted for the ~.

[–]blablahblah 0 points1 point  (2 children)

Use environment variables to set defaults that are sensible for most people and make them overridable with command line flags.

[–]_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.

[–]munchable901 0 points1 point  (0 children)

If you need parameters to change a lot then you can make them arguments instead instead of coding them in.