zoukankan      html  css  js  c++  java
  • python 脚本传递参数

    给python程序传递参数

    运行python脚本时有时需要执行实传递参数

    在linux下:

    [root@Test ~]# cat /opt/python.py 
    #!/usr/local/bin/python
    # -*- coding:utf-8 -*-
    
    import sys
    
    print(sys.argv[0])          #sys.argv[0] 类似于shell中的$0,但不是脚本名称,而是脚本的路径   
    print(sys.argv[1])          #sys.argv[1] 表示传入的第一个参数,既 hello
    
    #运行结果:
    
    [root@Test ~]# python /opt/python.py hello
    /opt/python.py       #打印argv[0]  脚本路径
    hello                      #打印argv[1]  传入的参数 hello

    在windows 下:

    打开CMD或powershell,切换到python脚本所在位置,使用python filename.py执行脚本

    #编辑  D:PythonStudypython.py
    #内容如下:
    #!/usr/bin/env python
    # -*-coding:utf-8 -*-
    
    import sys
    
    print(sys.argv[0])
    print(sys.argv[1])
    
    进入powershell  
    PS C:Windowssystem32> cd D:PythonStudy   #进入目录
    
    PS D:PythonStudy> python python.py     #执行python脚本 (未传参数)
    python.py                                                    #报错信息
    Traceback (most recent call last):
      File "python.py", line 7, in <module>
        print(sys.argv[1])
    IndexError: list index out of range
    
    PS D:PythonStudy> python python.py hello  #传入参数(正常运行)
    python.py
    hello
    
    或以绝对路径执行:
    PS D:PythonStudy> python D:PythonStudypython.py hello
    D:PythonStudypython.py
    hello
    

    PyCharm 下运行python脚本并传递参数

    编辑脚本:

    Alt + Shift + F10 执行

    报错

    传递参数的方法:

    Alt + Shift + F10 弹出

    选择:Edit configurations 弹出

    在左侧选择要传入参数的文件,在右侧Configuration-->Script parameters 中添加要传递的参数 --> RUN

    执行结果:

     
  • 相关阅读:
    Windows Phone 在读取网络图片之前先显示默认图片
    ios开发 点击文本(TextField)输入的时候向上推以及输入之后恢复的动画
    51nod 1019 逆序数
    hdu 5455 Fang Fang
    51nod 1027 大数乘法
    51nod 1006 最长公共子序列Lcs
    51nod 1066 Bash游戏
    51nod 1069 Nim游戏
    51nod 1049 最大子段和
    51nod 1072 威佐夫游戏
  • 原文地址:https://www.cnblogs.com/shona/p/11969790.html
Copyright © 2011-2022 走看看