[英]Executing python code with command line arguments?
I have python code that takes 3 command line arguments. 我有需要3个命令行参数的python代码。 I am on linux, and I can't figure out how to execute the file.
我在linux上,我不知道如何执行该文件。 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.
我已经使用python -m py_compile MyFile.py进行了编译,这会将MyFile.pyc文件放在桌面上,但是似乎没有什么可以执行的。 I have tried ./MyFile.pyc arg1 arg2 arg3, but the command line says permission denied.
我已经尝试过./MyFile.pyc arg1 arg2 arg3,但是命令行显示权限被拒绝。 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?
然后,我尝试了python MyFile.py arg1 arg2 arg3,即使Main的第一行是打印内容,命令行也可以接受但不打印任何内容? Am I somehow not printing correctly?
我是否无法正确打印? I really just need to be able to execute this 1 file and give it arguments.
我真的只需要能够执行此1文件并为其提供参数。
Invoking the python command with the script as the first argument, followed by your script arguments should work, eg python MyScript.py _args_
. 以脚本作为第一个参数调用python命令,然后调用脚本参数应该可以,例如
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_
. 或者,您可以在文件顶部添加一个shebang,然后使用
chmod +x <script>
使其可执行,然后可以使用./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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.