Python 命令行参数 linux
Python command line arguments linux
我有这个小程序(我知道有很多错误):
#!/usr/bin/python
import os.path
import sys
filearg = sys.argv[0]
if (filearg == ""):
filearg = input("")
else:
if (os.path.isfile(filearg)):
print "File exist"
else:
print"No file"
print filearg
print "wasn't found"
如果我通过键入 python file.py testfile.txt
来启动它
输出总是(即使文件不存在):
File exist
如果你不知道我想从这个程序中得到什么,我想打印 "File 'filename' wasn't found" 如果文件不存在,如果它存在我不想打印 "File exist"
有什么解决办法吗?
谢谢
应该是sys.argv[1]
而不是sys.argv[0]
:
filearg = sys.argv[1]
来自docs:
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
第一个参数始终是正在执行的文件的名称。许多编程语言都是如此,您需要使用 sys.argv[1]
我有这个小程序(我知道有很多错误):
#!/usr/bin/python
import os.path
import sys
filearg = sys.argv[0]
if (filearg == ""):
filearg = input("")
else:
if (os.path.isfile(filearg)):
print "File exist"
else:
print"No file"
print filearg
print "wasn't found"
如果我通过键入 python file.py testfile.txt
输出总是(即使文件不存在):
File exist
如果你不知道我想从这个程序中得到什么,我想打印 "File 'filename' wasn't found" 如果文件不存在,如果它存在我不想打印 "File exist"
有什么解决办法吗? 谢谢
应该是sys.argv[1]
而不是sys.argv[0]
:
filearg = sys.argv[1]
来自docs:
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
第一个参数始终是正在执行的文件的名称。许多编程语言都是如此,您需要使用 sys.argv[1]