shell脚本怎么调用python的return值

我在python下写了一个比较字符串的python函数如下:

import time

if name == "__main__":
fo = open("steps.txt", "r+")
steps = fo.read()
print "读取的step是 : ", steps
fo.close()

T0 = 0
X = 600
ticks = time.time()
T = (long(ticks) - T0) / X
step = str(T).upper()
while len(step) < 16:
    step = "0" + step

def compare():
    if steps == step:
        return 1
    else:
        return 0

compare()

然后我想在shell脚本里调用这个compare.py获取函数return的值
代码如下:
#!/bin/bash
var1=python compare.py
echo $var1
$var1并没有输出我想看到的return值1或0,而是执行了整个py文件
我只想接受这个return值有什么好的方法吗

2个回答

weijingpeng1
weijingpeng1 回复柳罐罐: 请问 有解决方案了没
大约一年之前 回复
weixin_42340144
柳罐罐 感谢解答!!!
接近 2 年之前 回复

python调用shell脚本的返回值处理几种方式:

shell脚本准备 hello.sh:
echo "hello world!"
echo "succeed";

  1. 使用os.system返回执行状态值 #------------------------------------------ #一、执行shell命令的状态返回值 #------------------------------------------ v_return_status=os.system( 'sh hello.sh') print "v_return_status=" +str(v_return_status)

输出结果:
hello world!
succeed
v_return_status=0

  1. 使用os.popen返回结果

    无返回终端,只打印输出内容
    #------------------------------------------
    #二(一)、获取shell print 语句内容一次性打印
    #------------------------------------------
    p=os.popen('sh hello.sh')
    x=p.read()
    print x
    p.close()

#------------------------------------------
#二(二)、获取shell print 语句内容,按照行读取打印
#------------------------------------------
p=os.popen('sh hello.sh')
x=p.readlines()
for line in x:
print 'ssss='+line

输出结果:

hello world!
succeed

ssss=hello world!

ssss=succeed
3. 使用commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
#------------------------------------------
#三、尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
#------------------------------------------
(status, output) = commands.getstatusoutput('sh hello.sh')
print status, output

输出结果:

0 hello world!
succeed

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
使用golang从命令行将输入读取到Shell脚本exec中

<div class="post-text" itemprop="text"> <p>I am using go to run a shell script using exec.command like below and I want to take an input argument using command line say <code>i</code>, and my output should be based on <code>i</code>, how would I do that? </p> <pre><code>i := os.Args[1:2] out, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log | awk '{print $i/1024}' &gt;&gt; mem_usage.csv").Output() if err != nil { fmt.Println(err.Error()) return } </code></pre> <p>How could I use that i in the shell script? </p> <p>Without <code>i</code> it works fine i.e if I put <code>$1</code> or <code>$2</code> it works fine but I want user to give me the position of <code>i</code> and then calculate accordingly.</p> </div>

通过Golang执行Shell脚本后找回错误

<div class="post-text" itemprop="text"> <p>I have a simple shell script (named <code>copy.sh</code>) which looks like below:-</p> <pre><code>#! /bin/sh cp $1 $2 </code></pre> <p>I did <code>chmod 777 copy.sh</code>.</p> <p>I have a golang code which executes the above shell code:-</p> <pre><code>package main import ( "fmt" "os/exec" ) func main() { _, err := exec.Command("/Users/debraj/copy.sh", "/Users/debraj/temp.txt", "/Users/debraj/gotest/").Output() if err != nil { fmt.Println("Failed to execute command " + err.Error()) return } fmt.Printf(" Copy Successful - %v") } </code></pre> <p>The above code is showing be the below output:-</p> <pre><code>jabongs-MacBook-Pro-4:src debraj$ go run copyerr.go Failed to execute command exit status 1 jabongs-MacBook-Pro-4:src debraj$ </code></pre> <p>But the error I receive from shell script looks like below:-</p> <pre><code>jabongs-MacBook-Pro-4:~ debraj$ ./copy.sh /Users/debraj/temp.txt /Users/debraj/gotest/ cp: /Users/debraj/gotest/temp.txt: Permission denied </code></pre> <p>Can someone let me know how how can I get the same error message that is returned by the shell script?</p> <p>If I don;t do <code>chmod 777 copy.sh</code> and the file has permission as below:-</p> <pre><code>jabongs-MacBook-Pro-4:~ debraj$ ls -la copy.sh -rw-r--r-- 1 debraj staff 21 Sep 29 13:28 copy.sh </code></pre> <p>Then the golang code gives the output as given by the shell script. Can some also let me know why this is behaving like this?</p> <p>I am on</p> <ul> <li>Golang 1.7</li> <li>Mac OS X 10.11.4</li> </ul> </div>

如何用java执行shell脚本先kill掉进程然后再重新执行noup java -jar xxx.jar &的命令,我使用java执行shell脚本能kill 掉进程,但是后面重启命令没生效,shell脚本单独运行又是能正常kill掉然后重启的

相关脚本在下方 #!/bin/bash #jar包文件路径及名称(目录按照各自配置) APP_NAME=/home/alitest20200514.jar #日志文件路径及名称(目录按照各自配置) LOG_FILE=/home/monifashe.log #查询进程,并杀掉当前jar/java程序 pid=`ps -ef|grep $APP_NAME | grep -v grep | awk '{print $2}'` kill -9 $pid echo "$pid进程终止成功" sleep 2 #判断jar包文件是否存在,如果存在启动jar包,并时时查看启动日志 if test -e $APP_NAME then echo '文件存在,开始启动此程序...' # 启动jar包,指向日志文件,2>&1 & 表示打开或指向同一个日志文件 nohup java -jar $APP_NAME > $LOG_FILE 2>&1 & #实时查看启动日志(此处正在想办法启动成功后退出) tail -f $LOG_FILE #输出启动成功(上面的查看日志没有退出,所以执行不了,可以去掉) #echo '$APP_NAME 启动成功...' else echo '$APP_NAME 文件不存在,请检查。' fi 下方是java调用代码 /** * 带返回结果的命令执行 * @return */ public static void execCmdWithResult() { try { String cmd = "java_start.sh"; // String command = cmd; // //接收正常结果流 // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // //接收异常结果流 // ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); // CommandLine commandline = CommandLine.parse(command); // DefaultExecutor exec = new DefaultExecutor(); // exec.setExitValues(null); // //设置一分钟超时 // ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000); // exec.setWatchdog(watchdog); // PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream); // exec.setStreamHandler(streamHandler); // exec.execute(commandline); // //不同操作系统注意编码,否则结果乱码 // String out = outputStream.toString("utf-8"); // String error = errorStream.toString("utf-8"); ProcessBuilder pb = new ProcessBuilder("./"+cmd); pb.directory(new File("/home/")); int runningStatus = 0; String s = null; Process p = pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((s = stdInput.readLine()) != null) { System.out.println("正常:" + s); } while ((s = stdError.readLine()) != null) { System.out.println("不正常:" + s); } runningStatus = p.waitFor(); System.out.println("runningStatus:" + runningStatus); } catch (Exception e) { e.printStackTrace(); } }

java调用python脚本,中文变成问号

java代码: PythonInterpreter interpreter = new PythonInterpreter(); PySystemState sys = Py.getSystemState(); sys.path.add("C:\\Python27\\jython2.5.2\\Lib"); interpreter.execfile("F:\\Eclipse_WorkSpace\\eval\\src\\eval\\shell.py"); interpreter.exec("print contain('name:梁淘气',':淘气梁')"); python脚本: def contain(str,subStr):   print str   print subStr   if subStr in str:     return True   else:     return False 输出: name:??? :??? True 问题:中文变成了???,导致结果出错,该怎么解决,希望大牛赐教

spring boot项目中使用Runtime.exec()调用pyhton脚本没有反应

ubuntu环境下,在spring boot项目中使用Runtime.exec()去执行一个python脚本 没有反应,把这个执行命令单独拿出来执行是可以有结果的,而且把这段代码单独拿出 来写成一个java文件编译class去执行也可以执行pythone脚本;代码如下: ``` @RestController @RequestMapping("/executescript") public class ExecuteScript { @RequestMapping("/execpython") public Object execPython(){ File file = new File("/home/jysp/srr/RFCN-nanrui/tools/testXianjia.py"); if(file.exists()){ System.out.println("可以读取到非项目中脚本"); }else{ System.out.println("不可以读取到非项目中脚本"); return "不可以读取到非项目中脚本"; } try { Runtime runTime = Runtime.getRuntime(); runTime.exec("python2 /home/jysp/srr/RFCN-nanrui/tools/testXianjia.py"); System.out.println("启动脚本"); } catch (Exception e) { e.printStackTrace(); return "执行python脚本失败"; } return "执行python脚本成功"; } } ``` 执行这段代码没有报任何错误,会返回"执行python脚本成功",我当时想了是不是spring boot项目不能直接执行python脚本,又把这行命令写到一个shell脚本中去,shell脚本单独执行也会有正确返回结果,可是把执行命令放入上述代码中执行,又出现没反应的结果 ---------------------------------------------------------- 然后我又换了jython.jar的方式去调用,代码如下: ``` @RequestMapping("/execpython") public Object execPython(){ File file = new File("/home/jysp/srr/RFCN-nanrui/tools/testXianjia.py"); if(file.exists()){ System.out.println("可以读取到非项目中脚本"); }else{ System.out.println("不可以读取到非项目中脚本"); return "不可以读取到非项目中脚本"; } PythonInterpreter interpreter = new PythonInterpreter(); InputStream in = null; try { in = new FileInputStream("/home/jysp/srr/RFCN-nanrui/tools/testXianjia.py"); PySystemState sys = Py.getSystemState(); sys.path.add("/home/jysp/srr/RFCN-nanrui/tools"); interpreter.exec("import _init_paths"); interpreter.execfile(in); } catch (FileNotFoundException e) { e.printStackTrace(); return "未找到文件"; } catch (Exception e) { e.printStackTrace(); if(null!=in){ try { in.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return "执行python脚本失败"; } return "执行python脚本成功"; } ``` 这次执行起来报错了,出现的异常是ImportError: No module named os: ![图片说明](https://img-ask.csdn.net/upload/201901/03/1546507286_27950.png) 这是不是python环境变量的问题,java代码里要怎么去配置它的环境变量呢 python报ImportError: No module named os,我把那段python得代码贴出来 ``` 1 # -------------------------------------------------------- 2 # Fast R-CNN 3 # Copyright (c) 2015 Microsoft 4 # Licensed under The MIT License [see LICENSE for details] 5 # Written by Ross Girshick 6 # -------------------------------------------------------- 7 8 """Set up paths for Fast R-CNN.""" 9 10 import os.path as osp 11 import sys 12 13 def add_path(path): 14 if path not in sys.path: 15 sys.path.insert(0, path) 16 17 this_dir = osp.dirname(__file__) 18 19 # Add caffe to PYTHONPATH 20 caffe_path = osp.join(this_dir, '..', 'caffe', 'python') 21 add_path(caffe_path) 22 23 # Add lib to PYTHONPATH 24 lib_path = osp.join(this_dir, '..', 'lib') 25 add_path(lib_path) ``` 就是第十行import os.path as osp报的错,有谁知道这个os.path是在哪个路径下面得呀

shell中局部变量返回值的问题

![图片说明](https://img-ask.csdn.net/upload/201804/03/1522743185_254739.png) 编写了shell脚本,定义函数readDir想统计某一个目录下所有文件的总记录数。在while循环中可以计算出所有文件总记录数total=11,但是for循环外就只能取到预先定义的初始值total=0,调用函数之后,拿到的也是return回来的0,求高手指点

怎么让脚本出错就立即停止

大家看图,我在一个脚本里面,调用了n个脚本,但是我现在想要的是,只要其中一个脚本出错了,就在那个位置退出,不再继续往下执行。请问怎么做呢?![图片说明](https://img-ask.csdn.net/upload/201605/31/1464690532_791675.png)

Jsch执行Shell脚本 发送回车,in.available()=0

public SshTest(String host, String user, String passwd) throws Exception { jsch = new JSch(); session = jsch.getSession(user, host, 22); session.setPassword(passwd); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setConfig("userauth.gssapi-with-mic", "no"); session.setConfig("GSSAPIAuthentication", "no"); session.connect(15000); channel = (ChannelShell) session.openChannel("shell"); ((ChannelShell)channel).setXForwarding(false); ((ChannelShell)channel).setPty(false); channel.setInputStream(null); channel.connect(15000); System.out.println("ssh通道创建成功"); } public byte[] readEcho(String cmd) throws Exception { System.out.println("cmd:" + cmd); final PrintStream pstream = new PrintStream(channel.getOutputStream(), true); InputStream in = channel.getInputStream(); byte[] data = new byte[] {}; byte[] buf=new byte[1024]; pstream.println("\r\n"); //发送空格 pstream.flush(); Thread.currentThread().sleep(1000l); while(true){ int count = 0; while((count=in.available())>0){ //卡在这里 in.available()一直都是0, int len=in.read(buf, 0, 1024); if(len<0)break; System.out.print(new String(buf, 0, len)); if (data.length == 0) { data = Arrays.copyOf(buf, len); } else { int tlen = len + data.length; byte[] tmp = new byte[tlen]; System.arraycopy(data, 0, tmp, 0, data.length); System.arraycopy(buf, 0, tmp, data.length, len); data = tmp; } } if(channel.isClosed()){ if(in.available()>0) continue; System.out.println("exit-status: "+channel.getExitStatus()); break; } try{Thread.sleep(count==0?1000:100);}catch(Exception ee){} } in.close(); pstream.close(); channel.disconnect(); session.disconnect(); return data; }

golang:在远程服务器上执行shell命令

<div class="post-text" itemprop="text"> <p>I have 50 something Linux machines (RHEL). I want to run some commands on these machines from a go script running on a central machine. I have setup password-less ssh authentication to all of them from the central machine to all the remote machines. Though I'm open to non-ssh solutions too, though something secure is preferred.</p> <p>The commands being run would change over time. I would also want to process the output and return codes of commands being run on the remote machines in my script running on central machine.</p> <p>I only found this <a href="http://godoc.org/code.google.com/p/go.crypto/ssh#example-Dial" rel="nofollow">ssh package</a>, which supports only password authentication method, which is not good enough.</p> <p>Any other options?</p> </div>

从php调用的长时间运行的python脚本的输出返回未显示在网页上

<div class="post-text" itemprop="text"> <p>I am simply calling python script from my php program and I need to display the output return from python script to webpage. I am new to this, so I tried many ways to get the output return,</p> <p>1.</p> <pre><code>$command = escapeshellcmd('python script.py "ab" "cd" '); $output = shell_exec($command); </code></pre> <p>2.</p> <pre><code>$output = shell_exec('python script.py "ab" "cd" '); print $output; </code></pre> <p>3.</p> <pre><code>$command = system('python script.py "ab" "cd" ',$output); echo "output is ".$output; echo "command is".$command; </code></pre> <p>4.</p> <pre><code>$command = passthru ('python script.py "ab" "cd" '); $output = shell_exec($command); echo $output; </code></pre> <p>5.</p> <pre><code>exec('python script.py "ab" "cd" ', $output, $return_var); echo $output; echo $return_var; </code></pre> <p>If time taken taken by python script is less, then I able to get the output return to my php program and able to display on my web page.</p> <pre><code>print "Hello" print "world" </code></pre> <p>But when my python program is calling any background process, which taking more time and giving output after few seconds, then that parts are not returning to the php program.</p> <pre><code>print "Hello" returned_value=subprocess.check_output('ssh -p 29418 xyz.com --format=JSON', shell=True) print returned_value </code></pre> <p>I tried to include sleep in php program but it is not helping as output is already returned. Some posts suggested to use <code>Ajax</code> Whether that is the only and correct way to solve this question? </p> <p>Thanks in advance for your help or suggestion. </p> </div>

Android中调用shell命令;

public static int execCommand(String command) throws IOException { return execCommand(new String[] { "sh","-c", command }); } /** * Execute shell command * @param command Shell command array * @return Result * @throws IOException Throws when occurs #IOException */ public static int execCommand(String[] command) throws IOException { Log.d("Darrick", "command = "+command); int result = RESULT_FAIL; Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec(command); } 其中String command = "echo > 0 /sys/bus/platform/drivers/battery/Charging_switch";本来打算是应用检测到电量为100%时自动执行该命令,不让机器充电;但是实现不了,求高手解答;谢谢;

shell 无法获取命令的输出结果

shell 获取脚本的输出结果 百度了很多资料,依然无法得到我想要的答案 我本来是要执行这个命令 ./cspub/cs_client -c ./cspub//client/client.conf -f ./url_list/tgb 这条命令输出结果应该是 NOTICE: 12-04 22:35:46: * 0 [connect_scheduler:485] yq01-ps-beehive-agent118850.yq01:7455 NOTICE: 12-04 22:35:46: * 0 [main:1370] login succeed, task_id = 2495372168972472539 NOTICE: 12-04 22:35:46: * 0 [send_task:870] send 3200 urls. 0 online host num 31 也就是说4条结果,但是每次我获取结果的时候,只能获取到最后一行,“0 online host num 31” 其他三行无法获得 代码: #!/bin/bash A=`./cspub/cs_client -c ./cspub//client/client.conf -f ./url_list/tgbdaa` echo 'aaaaaaaaa' echo $A echo $? 输出结果: NOTICE: 12-04 22:40:59: * 0 [connect_scheduler:485] yq01-ps-beehive-agent118876.yq01:7455 NOTICE: 12-04 22:40:59: * 0 [main:1370] login succeed, task_id = 2495460135153963424 NOTICE: 12-04 22:40:59: * 0 [send_task:870] send 3200 urls. aaaaaaaaa online host num 31 0

调用python脚本的php脚本在ssh终端中工作,但在浏览器窗口中没有输出

<div class="post-text" itemprop="text"> <p>The following pieces of code when executed using php -f phptest.php gave the output (server is a GCP virtual instance running Centos7):</p> <p>[[1, 2, 3], [4, 5, 6], [7, 8, 9]]<br> string(34) "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"</p> <p>In the terminal window. On the other hand the same code when run using the server IP and appropriate URL gives:</p> <p>string(0) ""</p> <p>Here are the two scripts :</p> <pre><code>#!/usr/bin/env python def foo(): x=str([[1,2,3],[4,5,6],[7,8,9]]) return x x=foo() print(x) </code></pre> <p>and</p> <pre><code>&lt;?php $command = "python_location pyfile.py" escapeshellcmd($commmand); $output = shell_exec($command); $strout=print_r($output,true); echo($strout); var_dump($strout); ?&gt; </code></pre> <p>The server doesn't have a directory /var/log/apache2/error.log. Instead i was able to find /var/log/httpd/error_log which contains the following:</p> <p>[Sun Jun 16 05:04:34.269345 2019] [auth_digest:notice] [pid 21434] AH01757: generating secret for digest authentication ... [Sun Jun 16 05:04:34.284400 2019] [lbmethod_heartbeat:notice] [pid 21434] AH02282: No slotmem from mod_heartmonitor [Sun Jun 16 05:04:34.284500 2019] [mpm_prefork:notice] [pid 21434] AH00163: Apache/2.4.6 (CentOS) PHP/7.3.6 configured -- resuming normal operations [Sun Jun 16 05:04:34.284505 2019] [core:notice] [pid 21434] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Sun Jun 16 05:11:53.245377 2019] [autoindex:error] [pid 32206] [client 187.10.191.110:35833] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive [Sun Jun 16 07:08:12.657568 2019] [autoindex:error] [pid 32210] [client 138.99.101.198:49444] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive [Sun Jun 16 09:09:49.507235 2019] [autoindex:error] [pid 32209] [client 170.130.187.26:54699] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive [Sun Jun 16 09:10:47.289063 2019] [autoindex:error] [pid 32207] [client 190.29.16.112:57449] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive [Sun Jun 16 13:50:02.964126 2019] [autoindex:error] [pid 32209] [client 95.141.135.6:34567] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive [Sun Jun 16 14:27:36.383175 2019] [autoindex:error] [pid 32207] [client 139.162.119.197:35716] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive</p> <p>'server-generated directory index forbidden by Options directive' leads me to believe that this could possibly be changed through httpd.conf possibly?</p> <p>Ideally the output in the browser would match the one I get in the ssh terminal</p> <p>Thanks and Regards</p> </div>

请教一个linux shell脚本的意思

``` function maybe_prompt_user() { if $ASSUME_YES; then return 0 else read -p "$1" if [[ $REPLY =~ ^[Yy]$ ]]; then return 0 else return 1 fi fi } ``` 这段脚本是什么意思,没太看明白,哪位高手指点一下,谢谢!

从php运行shell脚本并查看完整进度?

<div class="post-text" itemprop="text"> <p>Is there a way to run a shell script from PHP and echo the results after progress is completed?</p> <p>Here is my shell script:</p> <p>(Its multilines - a few commands that have to be ran one after the other. )</p> <pre><code>cd cd /var/www/html/ npm uninstall gulp --save npm install gulp --save npm start </code></pre> <p>here's my currently functioning PHP script. It only outputs some of the progress and only outputs it when complete. I need a live preview of the progress.</p> <pre><code> &lt;?php echo "loaded&lt;br&gt;&lt;br&gt;"; // echo shell_exec("cd /var/www/html/.."); // rin the shell scrip from header_register_callback echo '&lt;pre&gt;'; // Outputs all the result of shellcommand "ls", and returns // the last output line into $last_line. Stores the return value // of the shell command in $retval. $last_line = system('cd /var/www/html/; npm start', $retval); // Printing additional info echo ' &lt;/pre&gt; &lt;hr /&gt;Last line of the output: ' . $last_line . ' &lt;hr /&gt;Return value: ' . $retval; ?&gt; </code></pre> </div>

如何通过php脚本调试shell进程执行?

<div class="post-text" itemprop="text"> <p>I have a php script which is supposed to execute a perl script on the machine and print the process ID. While executing it, I found that the process id was printed out, but on checking the process list, I couldnt find a running process for the perl script. </p> <p>I logged the command to a file, and found that the command is correct, and executing it from shell correctly executes the script. Both scripts are owned by www-data.</p> <pre><code>if (isset($_GET['path'])) { $spath=$_GET['path']; $cmd="/usr/bin/perl ".getcwd().'/rotten2torrent.pl "'.$spath.'"'; $outputfile="tmpfile"; $pidfile="pid"; if (isset($_GET['recursion'])) { $recursion=1; $cmd=getcwd().'/htmlrscrape.pl '.$spath; } else { $recursion=0; } $command = $cmd . ' &gt; /dev/null 2&gt;&amp;1 &amp; echo $!; '; $pid = exec($command, $output, $return); fwrite($logfile, " ". "Command: ".$cmd); print 'Download started with PID '.$pid; fwrite($logfile, " ". "Download started with PID ".$pid); fwrite($logfile, " ". "Output lines: ".$pid); fwrite($logfile, " ". "Return code: ".$return); foreach ($output as &amp;$value) { fwrite($logfile, " ". $value); } } </code></pre> <p>Log file output:</p> <pre><code>#cat dldebug.log http://www.rottentomatoes.com/top/bestofrt/top_100_horror_movies/?category=10 test Command: /usr/bin/perl /var/www/rotten2torrent.pl "http://www.rottentomatoes.com/top/bestofrt/top_100_horror_movies/?category=10" Download started with PID 13147 Output lines: 13147 Return code: 0 13147 Done </code></pre> <p>I also reviewed apache2 access and error logs, but it doesnt show errors:</p> <pre><code>tac /var/log/apache2/access.log | less ip1 - - [16/May/2015:12:18:13 +0530] "HEAD / HTTP/1.1" 200 285 "-" "Cloud mapping experiment. Contact research@pdrlabs.net" ip2 - - [16/May/2015:11:54:41 +0530] "GET /dlnow.php?path=http%3A%2F%2Fwww.rottentomatoes.com%2Ftop%2Fbestofrt%2Ftop_100_horror_movies%2F%3Fcategory%3D10&amp;action=test HTTP/1.1" 200 321 "http://199.204.187.162/dlbox.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36" </code></pre> <p>How can I debug this? I'm assuming that the shell process execution starts but is then killed by the system. How can I monitor what error is being shown? </p> <p>exec is not a disabled function in php.ini on my server. I have tested a 'ls -l' on the server with php exec and it is executed.</p> <p>I tried monitoring process execution with htop, but couldnt find the process starting.</p> </div>

Linux shell 监控进程重启失败

[root@GM]# ./protocol & [root@GM]# 当前线程栈大小:2097152; 栈最小:16384 Success to establish a socket... Success to bind the socket... isatty success! fd->open=5 Set Port Exactly! 上面可以正常执行, [root@GM]# cat delfile.sh ./protocol & 执行sh delfile.sh后程序报错 Set Port Exactly! SetupSerial 1: Bad file descriptor 报错部分代码 struct termios options; /*tcgetattr(fd,&options)得到与fd指向对象的相关参数,并将它们保存于options,该函数还可以测试配置是否正确,该串口是否可用等。若调用成功,函数返回值为0,若调用失败,函数返回值为1. */ if ( tcgetattr( fd,&options) != 0) { perror("SetupSerial 1"); return(FALSE); } 求大牛解答一下,为什么在shell执行就会报错呢,直接输命令就能正常执行! 谢谢!

执行在网页中使用PyAudio的python脚本

<div class="post-text" itemprop="text"> <p>I have a python script which uses pyaudio to record audio using microphone and the code converts speech to text.It works perfectly fine on terminal. Here is a section of the python code :</p> <pre><code>stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK) async def send_audio(ws): # Starts recording of microphone print("* READY *") start = time.time() while True: try: #print(".") data = stream.read(CHUNK) await ws.send(data) ##if time.time() - start &gt; 30: # Records for n seconds ##await ws.send(json.dumps({'action': 'stop'})) ##return False except Exception as e: print(e) return False except KeyboardInterrupt: # allow Ctrl + C to shut down the program await ws.send(json.dumps({'action': 'stop'})) return False # Stop the stream and terminate the recording stream.stop_stream() stream.close() p.terminate() async def speech_to_text(): async with websockets.connect(url, extra_headers=token_header) as conn: # Send request to watson and waits for the listening response send = await conn.send(json.dumps(params)) rec = await conn.recv() print(rec) asyncio.ensure_future(send_audio(conn)) w=0 global lst # Keeps receiving transcript until we have the final transcript while True: try: rec = await conn.recv() parsed = json.loads(rec) transcript = parsed["results"][0]["alternatives"][0]["transcript"] #print(parsed) if "results" in parsed: if len(parsed["results"]) &gt; 0: if "final" in parsed["results"][0]: if parsed["results"][0]["final"]: #conn.close() #return False print(transcript) lst.append(transcript) lst.append(" ") pass except KeyError: conn.close() return False # Starts the application loop loop = asyncio.get_event_loop() loop.run_until_complete(speech_to_text()) loop.close() </code></pre> <p>Now,I want to call this script in a web page by clicking a button.I tried using exec() and shell_exec() in php as:</p> <pre><code>&lt;div&gt; &lt;?php echo "&lt;h3&gt;POST:&lt;/h3&gt;"; print_r($_POST); if(isset($_POST["submit"])){ print_r (shell_exec("cd / &amp;&amp; python C:/xampp/htdocs/heyy/postibm.py")); } ?&gt; &lt;form method="post" action="try.php "&gt; &lt;input type="submit" name="submit" value="Submit"&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>But on clicking the button,the page is stuck on loading screen and gives no response.If I replace "postibm.py" with simple "helloworld.py" printing hello world,it works.Any idea where the problem is ? or any better ways to solve this?</p> </div>

java 调用shell 生成文件的问题,好困惑,弄了很多天了

public Callback exeShell(final Map<String, String> header, final Map<String, String> map){ Callback rb= new CallbackImpl(); String shellCommand = "python3 /home/vat/gfjj_report/makeexecl/report.py"; logger.info("shellCommand:"+shellCommand); //String[] cmd = {"/bin/sh", "-c", shellCommand}; String result = " "; BufferedReader br = null ; BufferedInputStream buis = null ; Process p; try { p = Runtime.getRuntime().exec(shellCommand); if(p.waitFor() != 0 ){ result += "没有进程号"; } buis = new BufferedInputStream(p.getInputStream()); br = new BufferedReader(new InputStreamReader(buis)); String lineStr ; while ((lineStr = br.readLine()) != null){ result += lineStr; } } catch (Exception e) { e.printStackTrace(); rb.setErrorCode("-1"); rb.setErrorMessage("生成失败,错误信息:" + e.getMessage()); return rb; }finally{ if(br != null){ try { br.close(); buis.close(); } catch (IOException e) { e.printStackTrace(); } } logger.info("ShellUtil.ExeShell =>"+ result); } return rb; } ``` ``` 其中类是这样写的,我有几个疑问。点击生成时不成功。 java.io.IOException: Cannot run program "python3": CreateProcess error=2, ϵͳÕҲ»µ½ָ¶ at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047) at java.lang.Runtime.exec(Runtime.java:617) at java.lang.Runtime.exec(Runtime.java:450) at java.lang.Runtime.exec(Runtime.java:347) at com.gingkoo.cust.server.GfjjCommonService.exeShell(GfjjCommonService.java:95) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.gingkoo.gui.data.server.command.executer.CommandExecutor.execute(CommandExecutor.java:136) at com.gingkoo.gui.data.server.GUIGWTServer.updateData(GUIGWTServer.java:1888) at com.gingkoo.gui.data.server.GUIGWTServer.updateData(GUIGWTServer.java:1) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1097) at com.gingkoo.gal.web.filter.LoggerContextFilter.doFilter(l:211) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1088) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488) Caused by: java.io.IOException: CreateProcess error=2, ϵͳÕҲ»µ½ָ¶ at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.<init>(ProcessImpl.java:385) at java.lang.ProcessImpl.start(ProcessImpl.java:136) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028) ... 41 more 报以上的错,我的脚本是:python3 /home/vat/gfjj_report/makeexecl/report.py 我怀疑是不是因为本地测试的原因,因为调用的是远程的shell.在网上找了很多答案,发现都没有解决好。

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

ArrayList源码分析(入门篇)

ArrayList源码分析 前言: 写这篇博客的主要原因是,在我上一次参加千牵科技Java实习生面试时,有被面试官问到ArrayList为什么查找的速度较快,插入和删除的速度较慢?当时我回答得不好,很大的一部分原因是因为我没有阅读过ArrayList源码,虽然最后收到Offer了,但我拒绝了,打算寒假学得再深入些再广泛些,下学期开学后再去投递其他更好的公司。为了更加深入理解ArrayList,也为

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

玩转springboot启动banner定义所得

最近接手了一个springboot项目,不是不熟悉这个框架,启动时打印的信息吸引了我。 这不是我熟悉的常用springboot的打印信息啊,我打开自己的项目: 还真是的,不用默认的感觉也挺高大上的。一时兴起,就去研究了一下源代码,还正是有些收获,稍后我会总结一下。正常情况下做为一个老程序员,是不会对这种小儿科感兴趣的,不就是一个控制台打印嘛。哈哈! 于是出于最初的好奇,研究了项目的源代码。看到

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

立即提问
相关内容推荐