-2

When I run this following lines as: python MyApp.py arg1 arg2 I get the expected result:

['MyApp.py', 'arg1', 'arg2']

BUT - when I run it as: MyApp.py arg1 arg2 I do not get the arguments:

['MyApp.py']

How cat I get the arguments without explicitly using python?

#!/usr/bin/python
import sys
if __name__ == "__main__": 
    print (sys.argv)
jophab
  • 5,356
  • 14
  • 41
  • 60
DuduArbel
  • 1,100
  • 1
  • 12
  • 25
  • 2
    " without explicitly using python" Huh? You are writing a Python script. What does that mean? – DeepSpace Dec 31 '16 at 20:06
  • Can you share more of your source file? I can't reproduce the issue you're talking about with the code you've provided. – Irisshpunk Dec 31 '16 at 20:07
  • This is all my code. I want to get the arguments without explicitly using python? – DuduArbel Dec 31 '16 at 20:09
  • Again. What do you mean by " without explicitly using python". You can't write a Python script without explicitly using Python. – DeepSpace Dec 31 '16 at 20:10
  • Try it with this shebang `#!/usr/bin/env python` – SudoKid Dec 31 '16 at 20:11
  • @DeepSpace He means in the terminal he does not want to have to type it like this `python MyApp.py arg1 arg2` he wants it to be ran like so `MyApp.py arg1 arg2`. – SudoKid Dec 31 '16 at 20:12
  • Yes. Thanks for the clarification... – DuduArbel Dec 31 '16 at 20:15
  • 1
    I copy-pasted your code and it works for me (on Windows 10 with Python 3.6) - maybe you have set up the default application for .py files in a weird way that overrides the arguments? – UnholySheep Dec 31 '16 at 20:20
  • What happens when you add the line: ` print ("Arguments should appear after this:") before the line ` print (sys.argv)` and run `MyApp.py arg1 arg2`? – Chris Larson Dec 31 '16 at 20:31
  • 1
    Possible duplicate of [How to execute Python scripts in Windows?](http://stackoverflow.com/questions/1934675/how-to-execute-python-scripts-in-windows) – Shubham Dec 31 '16 at 20:44

1 Answers1

-1

If you are using a Linux Distribution, open the Terminal and type

which python

You will get a path where your default Python executable is stored. Enter this path as a first line of your code with shebang, i.e., #!. For example, my path is: /usr/bin/python, then I can do the following:

#! /usr/bin/python

import sys
print sys.argv

now, in your terminal, go to the directory where the file is stored. Suppose the name of the file is check.py. Make it executable using the following command:

chmod +x check.py

Now you can run your program by typing: ./check.py arg1 arg2 and it will execute as it should.

For Windows, you need to make sure that Windows is associating the right Python executable to execute your .py files. Even if it's associated correctly, sometimes Windows stripes off arguments from the command.

I am not a very heavy Windows user. You can check this blog: http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/

Shubham
  • 2,847
  • 4
  • 24
  • 37