简体   繁体   English

bash命令通过cli正常运行,但未在python脚本中运行

[英]bash command runs through cli fine but not running inside python script

Here is python script it is program which gets current INTERNET speed from cli and saves it in a python variable 这是python脚本,它是从cli获取当前Internet速度并将其保存在python变量中的程序

from subprocess import PIPE, Popen

def cmdline(command):
    process = Popen(args=command,stdout=PIPE,shell=True)
    return process.communicate()[0]

aa=(cmdline("awk '{if(l1){print ($2-l1)/1024,($10-l2)/1024} else{l1=$2; l2=$10;}}' <(grep eth0 /proc/net/dev) <(sleep 1); <(grep eth0 /proc/net/dev)"))

print(str(aa))

gives error 给出错误

/bin/sh: 1: Syntax error: "(" unexpected

Popen executes its command by default with /bin/sh , the POSIX shell. Popen默认使用POSIX shell /bin/sh执行其命令。 It does not recognize the bash extension <(...) , which leads to your error. 它无法识别bash扩展名<(...) ,这会导致您出错。 The quickest fix is to specify that you want to use /bin/bash as the shell: 最快的解决方法是指定您要使用/bin/bash作为外壳程序:

process = Popen(args=command, stdout=PIPE, shell=True, executable="/bin/bash")

A better solution would be to stick with a POSIX-compatible command, so that your Python script doesn't rely on bash being installed in any particular location, or at all. 更好的解决方案是坚持使用与POSIX兼容的命令,以使您的Python脚本完全不依赖于安装在任何特定位置的bash Something like 就像是

cmd = '''{
  grep eth0 /proc/net/dev
  sleep 1
  grep eth0 /proc/net/dev
  } | awk '{if(l1){print ($2-l1)/1024,($10-l2)/1024} else{l1=$2; l2=$10;}}'
'''


aa=(cmdline(cmd))

The best solution would be to figure out how to do what you want in Python itself, instead of embedding a shell script. 最好的解决方案是弄清楚如何在Python本身中执行所需的操作,而不是嵌入shell脚本。

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

相关问题 bash命令未通过python运行 - bash command not running through python 命令在终端或bash脚本中运行正常,但在使用子流程模块的python脚本中运行不正常 - Command works fine from terminal or inside bash script but not from python script using subprocess module (/ bin / bash:python3:找不到命令)在Matlab中通过系统命令运行python脚本时 - (/bin/bash: python3: command not found) When running python script through system command in Matlab 运行一个PHP脚本,该脚本运行一个运行bash脚本的Python脚本,并挂在bash上 - Running a PHP script that runs a Python script that runs a bash script, hangs on bash 在bash脚本中运行Python脚本 - Running Python script inside bash script 在 Windows 上通过 bash 命令运行 Python 代码 - Running a Python code through bash command on windows 在 Python 脚本中循环运行 Bash 命令 - Running a Bash Command in a loop in a Python Script NameError when running Python script through Bash - NameError When Running Python script through Bash Docker 容器中的 Python 脚本在不通过 Docker CLI 手动调用时运行良好 - Python script in Docker container runs fine when called manually not via Docker CLI 无法从Python运行的bash脚本运行bash命令 - Trouble running bash command from bash script run from Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM