skrmeme
skrmeme

Reputation: 3

Cannot get sys.argv to give any output in cmd

This may seem really basic, but for some reason I cannot get any program with sys.argv to print in command line. Instead, a new cmd window is very quickly opened, displaying no text within itself, then closed. Immediately after this, cmd skips a line and prints C:\Users\(my userid)>, awaiting a new input.

my code is as follows:

first I tried:

import sys

print(sys.argv)

and ran it via command line by inputting:

C:\Users\(my userId)\Desktop\filename.py(the location of the file)

There was no output, and instead cmd did what I described in the first paragraph.

I next tried:

import sys

def main():
    print(sys.argv)

if __name__ == '__main__':
    main()

and ran it via command line the exact same way. Again, I was greeted to the process described in the first paragraph.

I have checked that I have installed python the correct way, that the filenames are correct, and that the files are where they should be, generally speaking. I am running python 3.9.

Just inputting the filename results in the expected cmd output of:

'filename.py' is not recognized as an internal or external command,
operable program or batch file.

Any help is appreciated.

Edit: moving the python file directly to C:\Users(my userID), then running it in cmd using filename.py results in the same issue as before, on both versions of the program.

Upvotes: 0

Views: 601

Answers (2)

william
william

Reputation: 52

First of all, sys.argv returns a list. The list[0] will be the your program filename and the rest (list1, list[2], etc..) will be the arguments you input from the cmd line.

import sys
import time
def main():
  print(sys.argv[1])   # this will print out the first argument you input.
  time.sleep(3)        # in this case, sleep() is used to visualize the result in cmd.3 seconds in my case

if __name__ == '__main__':
  main()

I hope this will help you out! Further Resource

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

You have to actually run Python with python filename.py or python3 filename.py or py filename.py. This starts the interpreter and passes it the name of your file. The interpreter then executes the contents of your file.

C:\Users\TigerhawkT3>file.py
'file.py' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\TigerhawkT3>py file.py
['file.py']

Upvotes: 0

Related Questions