gpt4 book ai didi

Python 命令行参数 linux

转载 作者:太空狗 更新时间:2023-10-29 11:23:54 27 4
gpt4 key购买 nike

我有这个小程序(我知道有很多错误):

#!/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

如果你不知道我想从这个程序中得到什么,我想打印“找不到文件‘文件名’”如果文件不存在,如果它存在我不想打印“文件存在” "

有什么解决办法吗?谢谢

最佳答案

应该是 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.

关于Python 命令行参数 linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30482106/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com