简体   繁体   中英

Command-line input

I need to write a complete program that obtains three pieces of data and then process them. The three pieces of information are a Boolean value, a string, and an integer. The logic of the program is this: if the Boolean value is True, print out the string twice, once with double quotes and once without - otherwise print out twice the number. Which I can do just fine, but then I have to write the same program but this time using command-line input, the program below is what I have so far but i keep getting a command not found error.I feel like my "for i in range" is the error

 import sys

 def main():
     x = sys.argv[0].lower() == 'true'
     y = str(sys.argv[1])
     z = int(sys.argv[2])
     for i in range(0,len(sys.argv),1):
        print("   ",i,":",sys.argv[i])
     return 0;

"Command not found" is the shell response when a file is not in the $PATH or it was never made executable. First make sure that it is executable with

chmod +x myfile.py

second make sure that it is in your path with

which myfile.py

If it is not in your path, you need to execute it with an explicit path such as './myfile.py'

If it is not executable and you do not change it to executable you need to use

python [full path or .]/myfile.py

In your comment, you say that you execute it with "python3" doublecheck that it is the correct call for your system.

I almost forgot to add that the first line in your script needs to be

#!/usr/bin/python

or whatever python points to in your system

def main():
     x = sys.argv[1].lower() == 'true'
     y = str(sys.argv[2])
     z = int(sys.argv[3])
     if x:
         print "'{}'".format(y)
         print '"{}"'.format(y)
     else:
         print 2*z
     return 0;
if __name__ == '__main__':
     main()

save this as myfile.py
then from the shell run: chmod +x myfile.py && python myfile.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM