繁体   English   中英

在子进程输出的同一行上打印内容

[英]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尝试从字面上替换\\nr ,而不是控制字符。 这样可行:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM