1

i have a python script name as neural_net.py . It classify the mnist dataset. What i want to do is to run it via command line by taking input from user. The following snippet is taking input from user

file=input()
from PIL import Image
im = Image.open(file).convert('L')
imr=np.array(im).T
single_test = imr.reshape(1,400)
plt.figure(figsize=(5,5))
plt.imshow(imr)
print("value is",nn.predict(single_test))

in command prompt i have to run it as following

python neural_net.py

execute the above line and then give the input

pic_0.png

and it return me the output. What i want is to do the both of above things as a single command such as

python neural_net.py pic_0.png
2
  • use file = sys.argv[1] to get it. If you run with more arguments then you have sys.argv[2], etc. If you need more complex soluton like script.py --input pic_0.png --output image.png then see module argparse Commented Apr 28, 2019 at 1:11
  • i think you can use subprocess for it. Commented Feb 14, 2022 at 9:02

2 Answers 2

8

Use in code

import sys

file = sys.argv[1] 

to get it.

Now you can run it as

python neural_net.py pic_0.png

and file will be pic_0.png


If you run with more arguments

python neural_net.py pic_0.png pic_1.png pic_2.png 

then you will have sys.argv[2], sys.argv[3], etc. with values pic_1.png, pic_2.png


If you need more complex soluton like

script.py --input pic_0.png --output image.png 

then see module argparse

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input')
parser.add_argument('-o', '--output', default='output.png')
args = parser.parse_args()

file = args.input
output_file = args.output 
Sign up to request clarification or add additional context in comments.

Comments

1

EDIT: I think I realized why you are unhappy. You need to provide a path in addition to the file name, you can either do this with args like

python run.py "c:/users/user/desktop/pictures/pngs/file.png"

and use the original answers. Or simply just put a general path in the code and use the arg for the specific file.

IMAGE_FOLDER = "c:/users/user/desktop/pictures/pngs/"
file = IMAGE_FOLDER + sys.argv[1]

Original:

This is pretty much straight from google results:

CML:

    python neural_net.py pic_0.png

Code:

     import sys
     print sys.argv[1]

Result:

    "pic_0.png"

Many thanks for Google and https://www.pythonforbeginners.com/system/python-sys-argv

2 Comments

I'm not sure I understand the question, given this post and @furas, who also answered as I would've expected is also downvoted.
maybe someone understand question in different way and he downvoted answers. I think your answer is correct for this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.