python - 如何将 subprocess.call 的结果打印到 python 脚本中的文件

标签 python windows python-3.x command jira

我有一个 python 脚本,我在其中调用 JIRA API 并从 JIRA 获取一些东西,我想将其写到文件中。

cmd 中的这个命令工作正常

curl -D- -u username:password -X GET --data @file.json -H "Content-Type: application/json" http:URL >> output.json

但是,当我尝试在 Python 中做同样的事情时,它并没有写入我的文件(直接转到我的“出了点问题”)

#Runs curl script to get component
def write():
    name = 'output.json'

try:
    file= open(name, 'w')
    file.write(subprocess.call('curl -D- -u username:password -X GET --data @file.json -H "Content-Type: application/json" http:URL'))
    file.close()

except:
    print('something is wrong')
    sys.exit(0)
write()

我还尝试让它在下面写入变量的内容。

curler = (subprocess.call('curl -D- -u username:password -X GET --data @file.json -H "Content-Type: application/json" http:URL'))

def write():
    name = 'output.json'

try:
    file = open(name, 'w')
    file.write(curler)
    file.close()

except:
    print('something is wrong')
    sys.exit(0)
write()

我正在使用 Windows 7 和 Python 3

最佳答案

subprocess.call() 接受一个参数列表,只返回被调用进程的退出状态。我认为您正在尝试将标准输出重定向到一个文件:

curl = ['curl', '-D-', '-u', 'username:password', '-X', 'GET', '--data',
        '@file.json', '-H', 'Content-Type: application/json', 'http:URL']
with open('output.json', 'w') as file:
    status = subprocess.call(curl, stdout=file)

关于python - 如何将 subprocess.call 的结果打印到 python 脚本中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33043123/

相关文章:

python - 如何隐藏 PyQt4 Python 应用程序的任务栏图标?

windows - SVN 仓库备份策略

python - 在类上覆盖 dict()

python - Pandas/Python 过滤 DF 的列值

Python:根据匹配值从第二个列表添加元素

python - Visual Studio Code - 具有自动完成功能的 Python 交互式数据科学 REPL

python - python 中的异常处理和继续 for 循环

python: from __future__ import print_function 必须在每个加载的模块中?

c++ - Windows API 和 GetClassName()?另一个名字?

mysql - 不支持关键字