简体   繁体   中英

Executing python code with command line arguments?

I have python code that takes 3 command line arguments. I am on linux, and I can't figure out how to execute the file. I have compiled with python -m py_compile MyFile.py and this puts a MyFile.pyc file on my desktop, but there doesn't seem to be anything I can execute. I have tried ./MyFile.pyc arg1 arg2 arg3, but the command line says permission denied. I then tried python MyFile.py arg1 arg2 arg3, and the command line accepts this but doesn't print anything, even though the first line of Main is a print? Am I somehow not printing correctly? I really just need to be able to execute this 1 file and give it arguments.

Invoking the python command with the script as the first argument, followed by your script arguments should work, eg python MyScript.py _args_ .

As an alternative, you could add a shebang at the top of the file, and make it executable with chmod +x <script> , then you could run it with ./MyScript.py _args_ .

Take as a reference the following script, which should print the arguments received:

import sys

for n, arg in enumerate(sys.argv):
    print "Arg %d: %s" % (n, arg)

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