customize argparse with -help support - python-3.x

I would like to enable -help option to user. I found couple of example but did not any concrete direction.
import argparse
import os
import sys
def parse_args(args):
parser = argparse.ArgumentParser()
parser.add_argument("-upf", dest="upf", help="provide upf file full path")
args = parser.parse_args()
return args
def main(argv):
args = parse_args(argv)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
python test.py -help
"error: argument -h/--help: ignored explicit argument 'elp'

Related

how to pytest a pyqt application that uses argparse for input parameters

I have a PyQt application that uses argparse to pass some argument.
I managed to write a simple test to see if the app starts
but I cannot set/mock the argparse arguments
I know it because inside the code I have some try/except like this
try:
if args.erase_data:
pass
except NameError:
logger.error("Error in parsing erase_data input argument \n")
that during the tests fail, while they do not fail if I run the app.
I tried this to mock args
import os
import pathlib
# import pdb
import sys
from unittest import mock
import pytest
from PyQt5 import QtTest
from PyQt5.QtWidgets import *
from pytestqt.plugin import QtBot
sys.path.append(os.getcwd())
src_dir = pathlib.Path(__file__).parents[1].absolute()
print(src_dir)
sys.path.append(src_dir.as_posix())
GUI = __import__("GUI")
#pytest.fixture(scope="module")
def qtbot_session(qapp, request):
result = QtBot(qapp)
with capture_exceptions() as e:
print(getattr(e, "message", repr(e)))
yield result
print(" TEARDOWN qtbot")
#pytest.fixture(scope="module")
def Viewer(request):
with mock.patch.object(sys, "argv", ["",'-d','2']):
print("mocking sys argv")
print(sys.argv)
# pdb.set_trace()
app, app_window = GUI.main()
qtbotbis = QtBot(app)
QtTest.QTest.qWait(0.5 * 1000)
assert app_window.isVisible()
return app, app_window, qtbotbis
but args is still not set.
any idea how to solve it?

What is the SyntaxError in the a "def" line in a python script?

I am trying to run the follow python script:
#!/usr/bin/env python
#Author Jared Adolf-Bryfogle
#Python Imports
import os
import sys
from pathlib import Path
from typing import Union
#Append Python Path
p = os.path.split(os.path.abspath(__file__))[0]+"/src"
sys.path.append(p) #Allows all modules to use all other modules, without needing to update pythonpath
#Project Imports
from pic2.modules.chains.ProposedIgChain import ProposedIgChain
from pic2.modules.chains.IgChainSet import IgChainSet
from pic2.modules.chains.IgChainFactory import IgChainFactory
from pic2.modules.chains.AbChainFactory import AbChainFactory
from pic2.tools.fasta import *
class IgClassifyFASTA:
"""
Identify CDRs from a Fasta File
"""
def __init__(self, fasta_path: Union[Path, str]):
self.fasta_path = str(fasta_path)
self.outdir = os.getcwd()
self.outname = "classified"
self.fasta_paths = split_fasta_from_fasta(os.path.abspath(self.fasta_path), "user_fasta_split_"+self.outname, self.outdir)
def __exit__(self):
for path in self.fasta_paths:
if os.path.exists(path):
os.remove(path)
def set_output_path(self, outdir: Union[Path, str]):
self.outdir = str(outdir)
def set_output_name(self, outname: Union[Path, str]):
self.outname = str(outname)
My python version is 3.8, and the pic2 is a conda env. I get the the following error:
File "IgClassifyFASTA.py", line 29
def __init__(self, fasta_path:Union[Path, str]):
SyntaxError: invalid syntax
I cannot figure out what's wrong with this line. Could you kindly give me some hint what's the wrong lying in? I will appreciate any help.
Best regards!

Conditional choices of an argument based on a preceding argument

I want to create a script that takes two arguments that should be consumed:
directory_path,
files -- the list of files under the directory_path argument.
I've written something like that:
#!/usr/bin/python3
import argparse
import os
import argcomplete
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("directory_path",
help="a path to some directory",
nargs=1)
# conditional choices of an argument
conditional_choices = [os.listdir(parser.parse_known_args()[0].directory_path[0])]
parser.add_argument("files",
metavar="FILES",
nargs='+',
choices=conditional_choices)
argcomplete.autocomplete(parser)
args = parser.parse_args()
print("directory_path {}".format(args.directory_path))
print("files {}".format(args.files))
So the files argument depends on the directory_path argument.
Using: Python3.8
Problems
For the above snippet, the bash-completion (built from register-python-argcomplete3) for a files argument doesn't work.
If I push enter after the valid command (with path and file) then I'm getting an error
error: argument FILES: invalid choice: ...
First is worth step in argcomplete documentation based on which I created a solution
#!/usr/bin/python3
# PYTHON_ARGCOMPLETE_OK
import argparse
import os
import argcomplete
def files_names(prefix, parsed_args, **kwargs):
absolute_pat = os.path.abspath(parsed_args.directory_path[0])
files = [file for file in os.listdir(absolute_pat) if os.path.isfile(os.path.join(absolute_pat, file))]
return files
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("directory_path",
help="a path to some directory",
nargs=1)
parser.add_argument("files",
metavar="FILES",
nargs='+').completer = files_names
argcomplete.autocomplete(parser)
args = parser.parse_args()
print("directory_path {}".format(args.directory_path))
print("files {}".format(args.files))
*usesfull snippet from argcomplete test directory
To debugging the completion you can set the _ARC_DEBUG variable in your shell to enable verbose debug output

selenium+argparse - change browser with command line argument

I want to create a selenium script and use argparse to choose the browser from the command line. This is what I have - when I run test.py chrome, nothing happens.
test.py:
https://repl.it/repls/ProbableHeavenlySystem
from selenium import webdriver
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('chrome')
parser.add_argument('firefox')
parser.parse_args()
args = parser.parse_args()
def pick_browser(args):
if args.chrome == 'chrome':
return args.webdriver.Chrome(executable_path='C:/pathto/chromedriver.exe')
elif args.firefox == 'firefox':
return args.webdriver.Firefox(
executable_path='C:/pathto/geckodriver.exe')
if __name__ == '__main__':
main()
Thanks for your help !
You can use sys.argv:
import sys
print(sys.argv)
in command line type python script.py chrome and in script file:
import sys
print(sys.argv[1]) # prints chrome
Here you can find a good tutorial.

Python3 read args from file in Linux

I have program.py that accepts only one argument as URL:
python3 program.py http://www.xxx.xxx
and the code is something like this
def Video(url)
#do something
#with that url string
def Main():
parser = argparse.ArgumentParser()
parser.add_argument("url", help="Add URL", type=str)
args = parser.parse_args()
Video(args.url) # here most the list of urls from file
if __name__ == '__main__':
Main()
But I would like my program to read the URL from a file, one after the other has ended
Something like this:
Python3 program.py < URLfile
Thanks
import sys
for url in sys.stdin.readlines():
do_something(url.strip())
I think configparser is what you need.
Flexible format:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
done
parser = argparse.ArgumentParser()
parser.add_argument('url', nargs='+', type=str)
args = vars(parser.parse_args())
for x in args['url']:
Video(x)
if __name__ == '__main__':
Main()
and to use it:
python3 program.py $(<links)

Resources