[python] Does Python have an argc argument?

I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine).

In the C programs I used the code:

if (argc != 2) {
    /* exit program */
}

Question: What is used in Python to check the number of arguments

#!/usr/bin/python
import sys
try:
    in_file = open(sys.argv[1], "r")
except:
    sys.exit("ERROR. Did you make a mistake in the spelling")
text = in_file.read()
print text
in_file.close()

Current output:

./python names.txt = Displays text file (correct)
./python nam = error message: stated from the sys.ext line (correct)
./python = error message: stated from the sys.ext line (wrong: want it to be a
separate error message stating *no file name input*)

This question is related to python linux file-io error-handling arguments

The answer is


I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:

[filename] = sys.argv[1:]

in_file = open(filename)   # Don't need the "r"

This will assign the one argument to filename and raise an exception if there isn't exactly one argument.


You're better off looking at argparse for argument parsing.

http://docs.python.org/dev/library/argparse.html

Just makes it easy, no need to do the heavy lifting yourself.


dir(sys) says no. len(sys.argv) works, but in Python it is better to ask for forgiveness than permission, so

#!/usr/bin/python
import sys
try:
    in_file = open(sys.argv[1], "r")
except:
    sys.exit("ERROR. Can't read supplied filename.")
text = in_file.read()
print(text)
in_file.close()

works fine and is shorter.

If you're going to exit anyway, this would be better:

#!/usr/bin/python
import sys
text = open(sys.argv[1], "r").read()
print(text)

I'm using print() so it works in 2.7 as well as Python 3.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to error-handling

must declare a named package eclipse because this compilation unit is associated to the named module Error:Failed to open zip file. Gradle's dependency cache may be corrupt What does 'index 0 is out of bounds for axis 0 with size 0' mean? What's the source of Error: getaddrinfo EAI_AGAIN? Error handling with try and catch in Laravel What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? Raise error in a Bash script Javascript Uncaught TypeError: Cannot read property '0' of undefined Multiple values in single-value context IndexError: too many indices for array

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python