【问题标题】:Executing curl statement using subprocess in Python script not working在 Python 脚本中使用子进程执行 curl 语句不起作用
【发布时间】:2017-01-17 15:42:07
【问题描述】:

我正在尝试从 Python 脚本运行以下 curl 语句,以便使用 slack API 上传文件:

curl -F file=@test.csv -F channels=#general -F token=xxxx-xxxxxxxxx-xxxx https://slack.com/api/files.upload

当我从终端运行上述命令时,它成功地将正确的文件上传到#general 频道。但是,当我尝试使用以下代码从我的 Python 脚本运行它时,我收到一条错误消息:

bash_cmd = 'curl -F file=@test.csv -F channels=#general -F token=xxxx-xxxxxxxxx-xxxx https://slack.com/api/files.upload'
process = subprocess.Popen(bash_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stout, sterr = process.communicate()

错误回溯:

Traceback (most recent call last):
File "trendbot.py", line 75, in <module>
handle_command(command, channel)
File "trendbot.py", line 47, in handle_command
process = subprocess.Popen(bash_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
File "/Users/melanie/anaconda/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/Users/melanie/anaconda/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

如果我打印bash_cmd 并将其粘贴到我的终端窗口中,它也会成功运行。所有帮助表示赞赏。

【问题讨论】:

    标签: python curl subprocess


    【解决方案1】:

    回答我自己的问题:

    我必须设置shell=True,因为我的bash_cmd 是一个字符串。现在我运行以下命令,它可以工作:

    bash_cmd = 'curl -F file=@test.csv -F channels=#general -F token=xxxx-xxxxxxxxx-xxxx https://slack.com/api/files.upload'.format(file_name, channel)
    process = subprocess.Popen(bash_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stout, sterr = process.communicate()
    

    【讨论】:

      猜你喜欢
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多