问题
I was wondering whether it is possible to run a python script as a bash job after using argparse? I tried doing this by first passing an argument in the python script file using argparse and then I used the command:
bash bash1.sh
to run the bash file that will run the python script file. This resulted in an error
message_script.py: error: too few arguments
This error resulted from the fact that the argparse argument wasn't recognised. Is there any way I can get to pass the argument using argparse then run the python script as a batch job?
Content of message_script.py:
import sys
import random
import numpy as np
import argparse
from PIL import Image
import matplotlib.pyplot as plt
#Input of Data File
#Proprtion Alpha
parser = argparse.ArgumentParser()
parser.add_argument("Alpha", help = "proportion of pixels to be embedded in cover image")
args = parser.parse_args()
alpha = args.Alpha
alpha = float(alpha) #args.alpha came back as a string hence needed to be converted to float
#n is the number of pixels in cover image
n = 512*512 #since all images in BossBase testbench are 512 by 512
#Length of message to be embedded in cover image
length_msg = (alpha * n)
len_msg = int(length_msg)
#Generates a random message, a 1D vector consisting of 1s and 0s
msg = np.random.randint(2, size= len_msg)
#Save message in text format representing each bit as 0 or 1 on a separate line
msg_text_file = open("/home/ns3/PycharmProjects/untitled1/msg_file.txt", "w") #Path of Data File
msg_text_file.write("\n".join(map(lambda x: str(x), msg)))
msg_text_file .close()
Content of bash1.sh:
#!/bin/sh
python message_script.py
回答1:
You need to pass along the arguments to the python script. If you know the exact number of your arguments you can write smth like:
#!/bin/bash
# passing two arguments
python message_script.py "$1" "$2"
Or all of them:
#!/bin/bash
python message_script.py "$@"
来源:https://stackoverflow.com/questions/43819254/how-can-you-run-a-python-script-as-a-batch-job-after-passing-an-argument-using-a