Re: argparse — adding a --version flag in the face of positional args
More better:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("positional",type=int)
parser.add_argument('--version',action="version",version="2.0")
args = parser.parse_args()
# double argument
print(args.positional * 2)
From: Python-list on
behalf of Weatherby,Gerard
Date: Sunday, November 27, 2022 at 10:29 PM
To: Skip Montanaro , Python
Subject: Re: argparse — adding a --version flag in the face of positional args
Use two parsers:
import argparse
import sys
vparser = argparse.ArgumentParser(add_help=False)
vparser.add_argument('--version',action="store_true",help="show version")
# look for version, ignore remaining arguments
vargs, _ = vparser.parse_known_args()
if vargs.version:
print("Version 2.0")
sys.exit(0)
parser = argparse.ArgumentParser()
parser.add_argument("positional",type=int)
# add version again, so it displays if --help called
parser.add_argument('--version',action="store_true",help="show version")
args = parser.parse_args()
# double argument
print(args.positional * 2)
From: Python-list on
behalf of Skip Montanaro
Date: Sunday, November 27, 2022 at 6:42 PM
To: Python
Subject: argparse — adding a --version flag in the face of positional args
*** Attention: This is an external email. Use caution responding, opening
attachments or clicking on links. ***
I have a script to which I'd like to add a --version flag. It should print
the version number then exit, much in the same way --help prints the help
text then exits. I haven't been able to figure that out. I always get a
complaint about the required positional argument.
I think I could use something like nargs='*', but that would push off
detection of the presence of the positional arg to the application.
Shouldn't I be able to tell argparse I'm going to process --verbose, then
exit?
Thx,
Skip
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!k-JSWNRKr8fNARGIFw3z_eh_Kv0ouXZKTDEQfWplA3Y3yrLUl81TmbNLiuDiXGOjgXcmNFPOqU2Ldmsh1VCLvLsxBas$
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iuJxNp5rr6BjU2VBDXr3OC1kal6NmqPTePUyYJ3K9gvrkpd-O6LrEW77sZ1Km5k3eglgSURIu991H8zLO9n2APmf$
--
https://mail.python.org/mailman/listinfo/python-list
Re: argparse — adding a --version flag in the face of positional args
Thanks. It occurs to me that instead of providing two special actions
("help" and "version"), it might be worthwhile to provide a standard way of
saying, "if present, process this option and exit before considering other
details of the command line." Matt's example action works well enough for
my needs, but it would be nice if more than one such option could be given.
For example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("--version", version="777", action="version")
args = parser.parse_args(["--help", "--version"])
Which option is processed depends on their order on the command line. I
don't believe it's possible to run the script and see them both processed.
That's probably a secondary consideration though. My script is working well
enough in this regard now.
Skip
--
https://mail.python.org/mailman/listinfo/python-list
Re: argparse — adding a --version flag in the face of positional args
Mats Wichmann writes:
> On 11/27/22 16:40, Skip Montanaro wrote:
>> I have a script to which I'd like to add a --version flag. It should print
>> the version number then exit, much in the same way --help prints the help
>> text then exits. I haven't been able to figure that out. I always get a
>> complaint about the required positional argument.
>> I think I could use something like nargs='*', but that would push
>> off
>> detection of the presence of the positional arg to the application.
>> Shouldn't I be able to tell argparse I'm going to process --verbose, then
>> exit?
>
> ummm, hate to say this, but have you checked the documentation? this
> case is supported using an action named 'version' without doing very
> much.
I hadn't noticed the action 'version'. I just use
parser.add_argument(
"-v", "--version", action="store_true", dest="version",
help="print version"
)
...
if args.version:
print(f"Version {my_module.__version__}")
sys.exit(0)
where the version is specified in a pyproj.toml file and __init__.py
contains
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata
__version__ = importlib_metadata.version(__name__)
I use poetry to then build the corresponding versioned package.
What am I missing by not using the action 'version'? Do I just save
having to explicitly test for the version arg?
Cheers,
Loris
--
This signature is currently under constuction.
--
https://mail.python.org/mailman/listinfo/python-list
Setupfailure
May python failed to install -- https://mail.python.org/mailman/listinfo/python-list
Re: argparse — adding a --version flag in the face of positional args
On Sun, 27 Nov 2022 22:23:16 -0600, Karen Park declaimed the following: >I figured it out…there was a logistics file given with the assignment! I >thought it was supposed to be a download included with the python >download…oops! > I think you made this response in the wrong thread... -- Wulfraed Dennis Lee Bieber AF6VN [email protected]://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: argparse — adding a --version flag in the face of positional args
On Tue, 29 Nov 2022 at 12:37, Loris Bennett wrote: > > Mats Wichmann writes: > > > On 11/27/22 16:40, Skip Montanaro wrote: > >> I have a script to which I'd like to add a --version flag. It should print > >> the version number then exit, much in the same way --help prints the help > >> text then exits. I haven't been able to figure that out. I always get a > >> complaint about the required positional argument. > >> I think I could use something like nargs='*', but that would push > >> off > >> detection of the presence of the positional arg to the application. > >> Shouldn't I be able to tell argparse I'm going to process --verbose, then > >> exit? > > > > ummm, hate to say this, but have you checked the documentation? this > > case is supported using an action named 'version' without doing very > > much. > > I hadn't noticed the action 'version'. I just use > > parser.add_argument( > "-v", "--version", action="store_true", dest="version", > help="print version" > ) > That's still going to validate the rest of the args though - notably, you can't omit any mandatory arguments (like a subcommand). The version and help actions are implemented pretty simply, actually. They're just little action classes that do their action immediately on getting triggered. It should be easy enough to make any action you want that way. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Python script not letting go of files
I have a script which fetches a production site directly from a
Subversion repo using svn export
It runs a bunch of commands by calling this little method ...
def trycmd(cmd, log):
retcode = -1
ret = f"Trying {cmd}"
try:
retcode = os.system(cmd)
ret = f"\n{cmd} -ok-> {retcode}"
except Exception as err:
ret = f"\n{cmd} -fail-> {err}"
log.write(remove_password(ret))
return retcode
This is the fetching script (omitting variables at the top) which
appears to be keeping a finger on files which Apache wants.
with open(fetchlog, 'a') as log:
ret = f"\n\nFetching {tag}"
log.write(ret)
cmd = f"sudo rm -Rf {site_root}"
if trycmd(cmd, log) == 0:
cmd = f"sudo svn export --force --username {usr} --password
{pw} {svn_repo} {site_root}"
if trycmd(cmd, log) == 0:
# get any new dependencies
cmd = f"sudo -H pip install -r {reqfile}"
if trycmd(cmd, log) == 0:
# run any migrations shipped from the repo
cmd = f"sudo python3 {site_root}/manage.py migrate
--noinput --settings={settings}"
if trycmd(cmd, log) == 0:
# shouldn't find anything
cmd = f"sudo python3 {site_root}/manage.py
makemigrations --noinput --settings={settings}"
if trycmd(cmd, log) == 0:
# should have been done already
cmd = f"sudo python3 {site_root}/manage.py
migrate --noinput --settings={settings}"
if trycmd(cmd, log) == 0:
# remove all static files from their Apache dir
cmd = f"sudo rm -Rf {static_root}/*"
if trycmd(cmd, log) == 0:
# copy all static files to the Apache
location
cmd = f"sudo python3
{site_root}/manage.py collectstatic --noinput --settings={settings}"
if trycmd(cmd, log) == 0:
# set all permissions
cmd = f"sudo {scripts}/perms_{host}.sh"
if trycmd(cmd, log) == 0:
cmd = "sudo service apache2
restart"
if trycmd(cmd, log) == 0:
ret = f"\nFinish {tag}\n\n"
log.write(ret)
else:
print("Apache didn't restart")
else:
print("Didn't set permissions")
else:
print("Didn't collectstaic")
else:
print("Didn't delete static files")
else:
print("Didn't migrate 2")
else:
print("Didn't makemigration")
else:
print("Didn't migrate 1")
else:
print("Didn't install requirements")
else:
print("Didn't get source")
else:
print("Didn't remove site")
exit()
The problem I'm trying to fix is that after an Apache reload Apache
seems hellbent on filling up its scoreboard and running out of
resources. The kind folk on the Apache mailing list say something is
hogging the workers.
You can see the last operation above is an Apache restart. It should be
an Apache reload. Reload however lets Apache run out of resources.
Do any of you Python folks see any blunders in the above code along the
lines of not letting go of py files or static assets?
mod_wsgi is configured with 100% defaults.
mod_mpm_event conf per advice from the Apache mailing list is ...
ServerLimit 32
StartServers 16
MinSpareThreads 400
MaxSpareThreads 800
ThreadLimit 64
ThreadsPerChild 50
AsyncRequestWorkerFactor 2
MaxRequestWorkers 800
MaxConnectionsPerChild 0
Server Version: Apache/2.4.52 (Ubuntu 2022.04) OpenSSL/3.0.2
mod_wsgi/4.9.0 Python/3.10
Server MPM: event
Server Built: 2022-09-30T04:09:50
DigitalOcean droplet 8BG RAM and lightly loaded.
Many thanks for any hints.
Cheers
Mike
--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.
OpenPGP_signature
Description: OpenPGP digital signature
--
https://mail.python.org/mailman/listinfo
