【问题标题】:I'm getting trouble with subprocess.Popen and split command in python我在 python 中遇到 subprocess.Popen 和 split 命令的问题
【发布时间】:2021-06-21 10:57:35
【问题描述】:

实际上,我想编辑我的 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, 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(
    bash, test.sh, 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 - 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,那么你应该创建字符串"bash test.sh " + cmd。如果你不使用shell=True,那么你应该创建列表["bash", "test.sh", cmd]
  • 你能检查一下 Logger.info 和 Logger.error 是否需要更改。
  • Logger 不需要任何改动。
  • 我需要使用命令/shell bash test.sh -H GITHUB_OAUTH_TOKEN -r repo username
  • 正如我在回答中所说 - 你必须使用单个字符串 "bash test.sh -H GITHUB_OAUTH_TOKEN -r repo username"

标签: python bash bots telethon


【解决方案1】:

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

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

如果你不使用shell=True,那么你应该使用列表

 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", token, "-r", repo, 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

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2019-05-13
    • 2021-09-18
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多