我正在用Python实现一个Shell,我有一个小bug,我已经花了好几个小时试图修复这个bug,但却无法解决这个问题。你知道吗
当我运行我的程序并开始用“cat”命令键入一行时,一切正常,直到我在标准输出和文件名之间留出一个空格。你知道吗
例如:
1)cat <test >toto
运行得很好,现在toto有了内部测试。你知道吗
2)cat < test >toto
运行完美,现在toto拥有了测试内部的内容。你知道吗
3)cat < test > toto
运行得很好,现在toto有了内部测试,但是我在终端中得到了以下行(cat:toto:input file是output file)
4)cat <test > toto
不起作用,我得到同样的结果(cat:toto….)
当我在“>;”和文件名之间加一个空格时,怎么了?为什么它总是说输入文件和输出文件是一样的?! 这是我的密码
#!/usr/bin/python3
import os
import sys
from shutil import copyfile
def main():
while True:
sys.stdout.write("%% ")
line = input()
line2 = line[0:len(line)]
line = ""
dirs = os.listdir()
d = ""
for j in range(0, len(dirs)):
d += dirs[j] + " "
for i in range(0, len(line2)):
if line2[i] == "*":
line += d
else:
line += line2[i]
args=list(filter(None,line.split(" ")))
list_arg=[]
src=""
dst=""
sr_c=0
ds_t=0
cmd=args[0]
for temp in args:
if temp=="<":
sr_c=1
src=args[args.index("<")+1]
elif temp[0]=="<":
sr_c=1
src+=temp[1:]
elif temp==">":
ds_t=1
dst=args[args.index(">")+1]
elif temp[0]==">":
ds_t=1
dst+=temp[1:]
else:
list_arg+=[temp]
if ds_t:
output=os.open(dst,os.O_CREAT |os.O_WRONLY |os.O_TRUNC)
else: output=1
if sr_c:
inputt=os.open(src,os.O_RDONLY)
else: inputt=0
pid = os.fork()
if pid == 0:
os.dup2(inputt,0)
os.dup2(output,1)
os.execvp(cmd,list_arg)
else:
os.waitpid(pid,0)
sys.stdout.write("Bye!\n")
sys.exit(0)
main()
在
cat < test > toto
中,问题是您没有删除test
和toto
,所以您得到['cat', 'test', 'toto']
,然后将test
和toto
分配给stdin
,stdout
,所以最后系统将其视为cat test toto <test >toto
,所以您从toto
读取并写入toto
您可以使用
data = iter(args)
来创建iterator
,您可以像以前一样与for temp in data
一起使用,但也可以使用next(data)
从数据中获取下一个元素,for
将跳过此元素-因此它不会将此元素添加到list_arg
相关问题 更多 >
编程相关推荐