[英]print somthing on the same line as subprocess output
我想出了以下代碼:
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','')
但這並沒有改變任何東西
謝謝,Stefan
您通過使用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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.