我想出了以下代码:
import os, subprocess, sys
location = os.path.dirname(os.path.realpath(__file__))
file = os.path.basename(__file__)
#print location # + r'\' + file
user_in = raw_input(location + '>')
if user_in == 'cd ..':
proc = subprocess.Popen('cd .. && cd', shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin= subprocess.PIPE)
new_location = proc.stdout.read() + proc.stderr.read() + '>'
#new_location = str(new_location) + '>'
new_location = new_location.replace(r'\r','')
new_location = new_location.replace(' ','')
print new_location
#new_user_in = raw_input(str(new_location) + '>')
#subprocess.Popen('cd .. && ' + new_user_in, shell=True)
但是当我运行它并输入cd ..
时,我得到:
D:\Documents\Programmed\DesktopUnsorted
>
我不想要这个,因为我想要做的是:
D:\Documents\Programmed\DesktopUnsorted>
编辑
我也已经尝试过:new_location = new_location.replace(r'\n','')
但是它什么都不会改变
谢谢, 斯蒂芬
答案 0 :(得分:0)
您正在使用r
前缀来替代您的替代品。 Python尝试直接替换\n
和r
,而不是控制字符。可行:
new_location = new_location.replace('\r','')
无论如何,使用rstrip
会更好,因为它会删除所有结尾的空格/换行符/回车符:
new_location = proc.stdout.read().rstrip() + ">"
顺便说一句,您的Shell确实无法正常工作,因为子进程中的cd
不会更改当前python进程的目录。为此,您需要os.chdir
。
我会按原样改进它
user_toks = user_in.split()
if len(user_toks)==2 and user_toks[0]=="cd":
os.chdir(user_toks[1])
# next command
user_in = raw_input("{}> ".format(os.getcwd())