'Python Command Line Arguments Syntax Error
I am trying to print out the command line arguments, however when I try to have two print statements, I get a syntax error. Is there a reason for that?
This is my terminal input: python3 test.py example_Resume.pdf softwareengineering
Also, how would I deal with a command-line argument that has a space in between?
import sys
def main(argv):
{
print(f"Name of the script : {sys.argv[0]=}")
print(f"Arguments of the script : {sys.argv[1:]=}") // This line errors
}
if __name__ == "__main__":
main(sys.argv[1:])
Solution 1:[1]
The best way to deal with command-line arguments is to use argparse package which takes care of shell injection, optional, default arguments.
Documentation: Argpase
Here is a sample I use for projects.
import argparse
# >>>>>>>>>>>>>>>>>>>>>>> ARGUMENT PARSING <<<<<<<<<<<<<<<<<<<<<<<<<<<<
def args():
"""
Used to get the list of arguments paseed to the class
"""
parser = argparse.ArgumentParser()
parser.add_argument('-r','--raw_file',type=str,
help='It is used to get the raw input file for parsing',
required=True)
args = parser.parse_args()
return args.raw_file
def main():
# PARSED RAW FILE
raw_file=self.args()
if __name__ == '__main__':
main()
Solution 2:[2]
In addition to what the other commenters pointed out, your issue is with the curly braces.
I tried your code without them:
import sys
def main(argv):
print(f"Name of the script : {sys.argv[0]=}")
print(f"Arguments of the script : {sys.argv[1:]=}")
if __name__ == "__main__":
main(sys.argv[1:])
Curly braces mean something different in Python.
The question about passing the args when you don't use them in main is valid.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | High-Octane |
| Solution 2 | Avezou |
