简体   繁体   English

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

[英]how to execute shell command files in python

I am having trouble executing the following shell command.我在执行以下 shell 命令时遇到问题。 I'm in windows 10. I had to delete the user authorization here and left it as 'tktk' as i dind't want my authorization out here like that.我在 Windows 10 中。我不得不在这里删除用户授权并将其保留为“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

I stored the above command in a test.sh file I'm having trouble executing the above shell command.我将上述命令存储在 test.sh 文件中,但在执行上述 shell 命令时遇到问题。 It works on the linux terminal.它适用于 linux 终端。 But it doesn't work on my windows cmd.但它不适用于我的 Windows cmd。 I need to read the above url, get the json object and do some analysis with it.我需要阅读上面的 url,获取 json 对象并对其进行一些分析。

What i tried:我试过的:

import subprocess 
ans = subprocess.Popen(["bash",os.path.join(os.getcwd(), 'test.sh')])

This fails.这失败了。 ok...好的...

I tried then...我当时试了...

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

I'm getting error '%1 is not a valid Win32 application'我收到错误“%1 不是有效的 Win32 应用程序”

I copied your test.sh code into my own test.sh file, and tested a few different things.我将您的test.sh代码复制到我自己的test.sh文件中,并测试了一些不同的内容。

Try using os.system for calling your command instead of methods from subprocess .尝试使用os.system调用你的命令,而不是从方法subprocess

This worked for me:这对我有用:

import os
os.system(os.getcwd() + '/test.sh')

If you prefer os.path.join(os.getcwd(), 'test.sh') instead of what I have here, you can use that too, there's no major difference.如果你更喜欢os.path.join(os.getcwd(), 'test.sh')而不是我这里的,你也可以使用它,没有太大区别。

I hope this solves your problem :)我希望这能解决你的问题:)

try:尝试:

# Importing the necessary packages
$ from subprocess import call  

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM