1

I have a python program that runs perfectly in Sublime text. The main function in the file has an argument (integer argument).

def main(number = input())

But when I tried to run it in command line such as,

$python testFile.py 56

It is giving me nothing. How is it possible to send an integer in the command line?

4 Answers 4

5
def main():
    number = int(sys.argv[1])  # this line will fail if you pass an argument that's not an integer
    print(number)

if __name__ == "__main__":
    main()
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to import sys. And maybe do a check on len(sys.argv).
2

What you want is sys.argv.

def main(number):
  print int(number)

if __name__ == "__main__":
  main(sys.argv[1])

Then you will be able to pass what you want in $python testFile.py 56

Comments

0

Your issue is that you're invoking your testFile.py and providing an argument before your script has started (and read from def main()).

There are a handful of approaches you can use, but the easiest may be just using sys.argv to get command line arguments, e.g.

def main():
    number = int(sys.argv[1])

#this line calls main if you're calling the script directly:
if __name__ == '__main__':
    main()

Note that it's poor form to give a mutable argument (e.g. 'input()') as a default in a method's signature.

1 Comment

sys.argv is a list - might want to check your notation :)
0

As others have already suggested sys.argv can be used to get the command line arguments in your code.

But if for some odd reason you dont want to use that , you can also try passing the input using pipe in shell.

For example ,

$ echo '56' | python testFile.py

Comments

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.