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)
Related
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'
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
It doesn't create a pdf file in the directory also it prints - None
import sys
import subprocess
import re
def convert_to(folder, source, timeout=None):
args = [libreoffice_exec(), '--headless', '--convert-to', 'pdf', '--outdir', folder, source]
process = subprocess.run(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=timeout)
filename = re.search('-> (.*?) using filter', process.stdout.decode())
return filename
def libreoffice_exec():
# TODO: Provide support for more platforms
if sys.platform == 'darwin':
return '/Applications/LibreOffice.app/Contents/MacOS/soffice'
return 'libreoffice'
result = convert_to('/directory_to_save_file', '/File_path', timeout=15)
print(result)
Could anyone give me solution where I can easily convert docx to pdf? Thanks in advance!
You can try below code in your function
import subprocess
output = subprocess.check_output(['libreoffice', '--convert-to', 'pdf' ,'demo.docx'])
print output
I made a function in python3 which takes the path to some txt files and returns a list containing the name of all the txt files.
here is the function:
import os
def files(path):
folder = os.fsencode(path)
filenames = []
for file in os.listdir(folder):
filename = os.fsdecode(file)
if filename.endswith( ('.txt') ):
filenames.append(filename)
filenames.sort()
return filenames
to run this function I can do the following which works perfectly:
if __name__ == "__main__":
path = '/home/final_test'
file_list = files(path)
print(file_list)
but the problem is from this part. I am trying to make a script to run it in command-line using argparse. to do so I added the following code at the end of script but it does not return anything. do you know how to fix it?
def main():
ap = argparse.ArgumentParser(description="")
ap.add_argument('-P', '--path', required=True)
ap.add_argument('-o', '--outlist', required=True)
args = ap.parse_args()
file_list = files(path)
return file_list
if __name__ == "__main__":
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
try:
main()
except IOError as e:
if e.errno != 32:
raise
except KeyboardInterrupt as e:
pass
Your main() function returns None (due to empty return statement). Assuming your files function works OK and file_list get some value, after that line it is no longer used. Probably you want to print within main function file_list or return it to be accessible outside main function (assign it to other variable).
That said I don't see why you need signal lines.
You should print your result(?)
result = main()
print(result)
or
print(main())
Try this:
def main():
ap = argparse.ArgumentParser(description="")
ap.add_argument('-P', '--path', required=True)
#ap.add_argument('-o', '--outlist', required=True)
args = ap.parse_args()
print(args)
file_list = files(args.path)
return file_list
if __name__ == "__main__":
filelist = main()
print(filelist)
I corrected the if __name indenting; I print the return value from main; I set path correctly. And for debugging purposes Iprint(args)`.
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.