Python 调用 Apple Reporter JAR 文件回答运行时问题以检索令牌



Apple的Reporter API要求从2017年8月10日起获取令牌。我正在尝试通过在 Python 中调用 JAR 文件来自动化这一点,所以我使用子进程,我需要在运行时处理标准输出。 下面正在进行的工作给了我一个使用 WITH 的属性 EXIT 错误。我对其他方法持开放态度,因为到目前为止我无法回答运行时问题,因此我没有返回令牌。

import subprocess
from subprocess import Popen, PIPE
with subprocess.call(['java -jar Reporter.jar p=Reporter.properties sales.generateToken'], shell=True, stdin=PIPE, stdout=PIPE, universal_newlines=True) as p:
for line in p.stdout: 
if line.startswith("Please enter your username"):
answer = 'username'
elif line.startswith("Please enter your password"):
answer = 'password'
else:
continue # skip it
print(answer, p.stdin) # provide answer
p.stdin.flush()

您可以使用一个名为expect的魔法包!

这是expect.script应该的样子:

$ cat expect.script
#!/usr/bin/expect -f
spawn java -jar Reporter.jar p=Reporter.properties Sales.generateToken
expect -exact "Please enter your username: "
send -- "{username}r"
expect -exact "r
Please enter your password: "
send -- "{password}r"
expect -exact "r
If you generate a new access token, your existing token will be deleted. You will need to save your new access token within your properties file. Do you still want to continue? (y/n): "
send -- "yr"
expect eof

您可以使用 python 动态创建脚本文件,并使用它来与Reporter.jar进行交互

下面是一个示例:

import tempfile
import os
from subprocess import check_output
script_exp = """
#!/usr/bin/expect -f
spawn java -jar {reporter_jar_path} p={properties_file} Sales.generateToken
expect -exact "Please enter your username: "
send -- "{username}\r"
expect -exact "\r
Please enter your password: "
send -- "{password}\r"
expect -exact "\r
If you generate a new access token, your existing token will be deleted. You will need to save your new access token within your properties file. Do you still want to continue? (y/n): "
send -- "y\r"
expect eof
"""
output_folder = "/tmp/"
with tempfile.NamedTemporaryFile(suffix=".script", dir=output_folder) as script_file_obj:
script_file = os.path.basename(script_file_obj.name)
with open(os.path.join(output_folder, script_file), "wt") as out_file:
content = script_exp.format(
reporter_jar_path="Reports.jar",
properties_file="Reporter.properties",
username="username",
password="password"
)
out_file.write(content)
print(script_file)
args = ['/usr/bin/expect', script_file]
output = check_output(args, cwd=output_folder)
xml_response = b'<?xml' + output.split(b'<?xml')[-1]

或者,您可以使用纯python与Apple的HTTP端点进行交互。以下是一些示例:

https://github.com/fedoco/itc-reporter

https://github.com/chason/pytunes-reporter

最新更新