微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我在 python 中遇到 subprocess.Popen 和 split 命令的问题

如何解决我在 python 中遇到 subprocess.Popen 和 split 命令的问题

实际上我想编辑我的 python 脚本(用于运行 tg bot),这样当我触发命令时,它实际上在此之前有一些预定义的命令。就像不是输入整个命令一样,/run bash test.sh url 它应该适用于 /run url。简而言之,我希望 bash test.sh 已经在我的脚本中定义。看看原始脚本。

def shell(update: Update,context: CallbackContext):
message = update.effective_message
cmd = message.text.split(' ',1)
if len(cmd) == 1:
    message.reply_text('No command to execute was given.')
    return
cmd = cmd[1]
process = subprocess.Popen(
    cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
stdout,stderr = process.communicate()
reply = ''
stderr = stderr.decode()
stdout = stdout.decode()
if stdout:
    reply += f"*Stdout*\n`{stdout}`\n"
    LOGGER.info(f"Shell - {cmd} - {stdout}")
if stderr:
    reply += f"*Stderr*\n`{stderr}`\n"
    LOGGER.error(f"Shell - {cmd} - {stderr}")
if len(reply) > 3000:

现在我想让我的机器人预定义我的子进程命令的某些部分。就像我想将 bash test.sh 保持为预定义的那样,这样我就不必一次又一次地编写整个命令。我自己试过了。

def shell(update: Update,1)
if len(cmd) == 1:
    message.reply_text('No command to execute was given.')
    return
cmd = cmd[1]
process = subprocess.Popen(
    bash,test.sh,cmd,stderr = process.communicate()
reply = ''
stderr = stderr.decode()
stdout = stdout.decode()
if stdout:
    reply += f"*Stdout*\n`{stdout}`\n"
    LOGGER.info(f"Shell - bash test.sh {cmd} - {stdout}")
if stderr:
    reply += f"*Stderr*\n`{stderr}`\n"
    LOGGER.error(f"Shell - bash test.sh {cmd} - {stderr}")
if len(reply) > 3000:

但这对我不起作用,所以请帮助我获得正确的语法。

解决方法

如果你使用 shell=True 那么你应该使用单个字符串

 subprocess.Popen("bash test.sh " +  cmd,...,shell=True)

如果你不使用 shell=True 那么你应该使用 list

 subprocess.Popen(["bash","test.sh",cmd],shell=False) 

编辑:

script = 'test.sh'
token = 'AD........45'
repo = 'python-examples'
user = 'furas'

cmd = "bash {} -H {} -r {} {}".format(script,token,repo,user)
print(cmd)

cmd = f"bash {script} -H {token} -r {repo} {user}"
print(cmd)

data = ["bash",script,"-H","-r",user]
cmd = " ".join(data)
print(cmd)

结果:

bash test.sh -H AD........45 -r python-examples furas
bash test.sh -H AD........45 -r python-examples furas
bash test.sh -H AD........45 -r python-examples furas

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。