【问题标题】:print somthing on the same line as subprocess output在子进程输出的同一行打印一些东西
【发布时间】:2018-12-09 15:30:45
【问题描述】:

我想出了这个代码:

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','')

但它并没有改变任何东西

谢谢, 斯蒂芬

【问题讨论】:

  • 你可能也需要new_location.replace(r'\n','')
  • @Jean-FrançoisFabre 我已经试过了。但感谢您花时间提供帮助。我编辑了我的问题

标签: python python-2.7 subprocess


【解决方案1】:

您使用 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())

【讨论】:

  • 我知道它不会改变目录。该部分仅用于用户看到的内容,并且它只是我实际制作的代码的一部分。但是感谢我完全忘记了我使用 r 来带反斜杠的遮阳篷,否则我的其他代码将无法正常工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多