【Python学习笔记】关于sys.argv和C#与python的传参

参考的youtube视频链接


一开始觉得比起百度,Google搜索效率更高。现在发现,原来Youtube才是解决问题最高效的办法……感谢所有乐于分享的小伙伴们!!!


目录

1、属性
2、通过命令行添加元素
3、通过代码添加元素
4、关于IndexError报错的解释
5、关于用C#传参时遇到的bug
6、总结


1、属性

通过简单的代码试试看sys.argv的属性:

import sys

print(sys.argv)
print(type(sys.argv))

>>>
['d:/myPythonProject/demo/demo02.py']      //第一个print的输出      
<class 'list'>                             //第二个print的输出

所以:

  • 这个玩意儿是一个list
  • 永远存在sys.argv[0],存放着这个list的路径

will always be there and will always be a list

2、通过命令行添加元素

在terminal输入(编译器下方就有terminal,如果另外打开cmd需要改到当前代码的存放路径):

python demo02.py 1 2 3

>>>
['demo02.py', '1', '2', '3']

3、通过代码添加元素

代码:

import sys

name1 = sys.argv[1]
name2 = sys.argv[2]

print(name1)
print(name2)

不过仍然需要通过命令行传参(因为这本身就是用来接收参数的,现在没有别人传只好自己在命令行模拟):

python demo02.py linlan lanlynn

>>>
linlan
lanlynn

4、关于IndexError报错的解释

如果直接运行、或者没有写print()会怎么样呢?

Traceback (most recent call last):
  File "d:/myPythonProject/demo/demo02.py", line 3, in <module>
    name1 = sys.argv[1]
IndexError: list index out of range

这是因为sys.argv[]默认长度是1,而代码里却没有给sys.argv[1]sys.argv[2]赋值,因此会报错说“list的索引超出范围了”。报错的意思是,“I try to read the second item from the list but it's not there. There is no second item, so that's why we get an IndexError.”

(所有英文引用都来自视频中的小哥,感觉原文表达的意思更清楚就不翻译了)

What we could do in order to decide ahead of time whether it's safe to read the second and third argument (safe meaning that I know the arguments would be there).

所以这里可以做一个判断来“check ahead of time”:(假设需要输入两个参数)

if len(sys.argv) != 3:
    exit("please pass 2 arguments")

5、关于用C#传参时遇到的bug

报错:

C:UserslinlanAppDataLocalProgramsPythonPython38python.exe: can't open file 'D:myPythonProjectdemodemo01.py"2019-1-1"2019-1-22': [Errno 22] Invalid argument

明白了sys.argv的原理之后,很容易明白,这里报错是因为路径的问题。正常输入应该是python demo01.py 2019-1-1 2019-1-22,但是空格却被双引号代替了。
因此分析原因:问题出在输入数据的格式上,也就是这句话:

psi.Arguments = $""{script}""{start}""{end}"" ;

一开始不懂这一堆符号啥意思,现在明白了,肯定是代表空格什么的。再仔细想想,开头和末尾两个双引号肯定是引用String的作用,和格式本身没有关系。那么显然每段可以被分解为"{script}""{start}""{end}"

再一查,发现"是双引号"的转义字符。于是就明白了:相当于也是说明类型是String的作用,也就是"{script}""{start}""{end}"

不能直接用双引号而是要使用转义字符。肯定是和本身引用规则有关。

---->那么就明白了:原来是之前少了空格!(就是每两个"之间应该有个空格,否则读出来就变成双引号了)

所以加上空格就没有问题了:

psi.Arguments = $""{script}" "{start}" "{end}"" ;

6、总结

(抄自小哥笔记,懒得翻译了)

  • sys.argv is a list
  • sys.argv is always available
  • sys.argv will always have at least one item (a string with the program name)
  • any arguments passed at the command line will also be added to the sys.argv list
  • we can check to see if any arguments have been passed by checking the len() of sys.argv
原文地址:https://www.cnblogs.com/lanlynn/p/13387940.html