如何在python中执行shell命令文件

如何在python中执行shell命令文件,python,Python,我在执行以下shell命令时遇到问题。我在Windows10中。我不得不删除这里的用户授权,并将其保留为“tktk”,因为我不希望我的授权像那样出现在这里 curl 'https://pegasus-test.etflogic.io/portfolio/analyze' -H 'authority: pegasus-test.etflogic.io' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: applicatio

我在执行以下shell命令时遇到问题。我在Windows10中。我不得不删除这里的用户授权,并将其保留为“tktk”,因为我不希望我的授权像那样出现在这里

curl 'https://pegasus-test.etflogic.io/portfolio/analyze' -H 'authority: pegasus-test.etflogic.io' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: application/json' -H 'authorization: tktk' -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' -H 'content-type: application/json' -H 'origin: https://akita.etflogic.com' -H 'sec-fetch-site: cross-site' -H 'sec-fetch-mode: cors' -H 'referer: https://akita.etflogic.com/portfolio-analysis' -H 'accept-encoding: gzip, deflate, br' -H 'accept-language: en-US,en;q=0.9' --data-binary '{"portfolio":{"currency":"usd","id":"8576e266-c6f4-44fe-a6a6-9c64869b55dd","name":"test1","records":[{"locale":"US","id":"df92931e-3063-4889-8e4b-100c66f14d22","name":"SSGA SPDR S&P 500 - SSgA Active Trust","secid":549535,"size":100,"ticker":"SPY US"}],"size_type":"notional","type":"primary"}}' --compressed > /tmp/jsonpayload
我将上述命令存储在test.sh文件中 我在执行上面的shell命令时遇到问题。它在linux终端上工作。但它在我的windows cmd上不起作用。我需要阅读上面的url,获取json对象并对其进行一些分析

我尝试的是:

import subprocess 
ans = subprocess.Popen(["bash",os.path.join(os.getcwd(), 'test.sh')])
这是失败的。好的

我试过了

subprocess.call(['test.sh'])

我收到错误“%1”不是有效的Win32应用程序“

我将您的
test.sh
代码复制到我自己的
test.sh
文件中,并测试了一些不同的内容

尝试使用
os.system
调用您的命令,而不是
子流程中的方法

这对我很有用:

import os
os.system(os.getcwd() + '/test.sh')
如果您更喜欢
os.path.join(os.getcwd(),'test.sh')
而不是我这里的内容,您也可以使用它,没有什么大的区别

我希望这能解决您的问题:)

试试:

# Importing the necessary packages
$ from subprocess import call  

# Executing the test.sh script
$ call('sh test.sh 2>/dev/null', shell=True)

为什么不使用Python的
requests
模块而不是
curl
?可能是因为默认情况下
curl
不随windows提供。您是否尝试过为windows安装
curl
?是的。但是在从python调用shell命令之前,它仍然不能工作,我建议尝试从
cmd
或Powershell调用它。您是否在两次尝试中都得到“无效的Win32应用程序”?此操作失败。怎么会失败?我收到错误“%1”不是有效的Win32应用程序。这是整个错误消息吗?我不在工作。当我明天早上回来时,我会检查这个。感谢虽然此代码可能提供OP问题的解决方案,但强烈建议您提供有关此代码为什么和/或如何回答问题的其他上下文。从长远来看,纯代码的答案通常会变得毫无用处,因为未来遇到类似问题的观众无法理解解决方案背后的原因。