w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
execute cat command in subprocess,Popen() of python
The problem is that you're passing the command as multiple args. You need to pass them as a list or a tuple. Like: subp.Popen([ 'egrep','list_of_IDs','/home/bimlesh/python/result.log' ], stdout=subp.PIPE,stderr=subp.PIPE,shell=True)

Categories : Python

C Using popen to execute cmds on data
I ended up fixing it with this, just in case anyone else runs into a similar problem: FILE* pipe; if((pipe = _popen(cmdStr->c_str(), "w")) == NULL) { printf("Unable to create pipe! "); } fprintf(pipe, "%s", reply); printf(" Pipe process returned %d ", _pclose(pipe));

Categories : C

subprocess's Popen closes stdout/stderr filedescriptors used in another thread when Popen errors
I would like to answer your questions with: Yes. You shouldn't have to. No. The error occurs indeed in Python 2.7.4 as well. I think this is a bug in the library code. If you add a lock in your program and make sure that the two calls to subprocess.Popen are executed atomically, the error does not occur. @@ -1,32 +1,40 @@ import time import threading import subprocess +lock = threading.Lock() + def subprocesscall(): + lock.acquire() p = subprocess.Popen( ['ls', '-l'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) + lock.release() time.sleep(2) # simulate the Popen call takes some time to complete. out, err = p.communicate() print 'succeeding command in thread:', threading.current_t

Categories : Python

Is it necessary to call Popen.wait() to "clean up" after the Popen object?
No, you don't have to call wait if you are calling poll. They basically do the same thing, except that wait waits infinitely. poll: if self.returncode is None: if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: self.returncode = _GetExitCodeProcess(self._handle) return self.returncode wait: if self.returncode is None: _subprocess.WaitForSingleObject(self._handle, _subprocess.INFINITE) self.returncode = _subprocess.GetExitCodeProcess(self._handle) return self.returncode This is the code for windows implementation of the subprocess module, but all other should follow the same rules. On MacOS X and I assume the implementation for Linux is the same, they both call os.waitpid.

Categories : Python

Execute a ping to an address using Lua io.popen, non blocking if ping times out
io.popen is not going to work with copas. Copas is for sockets, not pipes. The quickest solution is to use polling; do e.g.: local socket = require "socket" local waitTime, sleepTime = 5, 0.1 local endT = os.time() + waitTime local result os.capture("ping myknowngoodip -c 1 > myoutfile") while os.time() <= endT do local pcall_ok, fHand = pcall(io.open, "myoutfile", "r") if pcall_ok then result = assert(fHand:read("*all")) assert(fHand:close()) end socket.sleep(sleepTime) end if result then -- Success! else -- Error :( end Another possibility is a separate thread; LuaLanes is the best multithreading toolkit out there, but also the biggest in terms of memory consumption. This is somewhat more involved, however. Another option is to implement

Categories : Lua

Delphi Pipes.PAS Incompatible with .NET Named Pipes?
So I got everything working, and here are some lessons when interfacing with Libby's Pipes.PAS : NamedPipeClientStream.IsMessageComplete will not work for you, ever. At least, it doesn't for me. Your reading thread/function needs to look something like : while(true) { if(pipeClient.CanRead) { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = pipeClient.Read(buffer, 0, BUFFER_SIZE); if(bytesRead > 0) ... Do stuff } } Libbys uses a custom protocol to signal multi-block sends : Multi-Block Start Packet: * 0x10 0x00 0x00 0x00 (4 bytes for length ... decimal 16) * 0x4d 0x41 0x47 0x43 (4 bytes for "MB_MAGIC" ... ASCII is "MAGC") * 0x53 0x54 0x4d 0x42 (4 bytes for "MB_START" control ... ASCII is "STMB" for Start Multi-block) * 0x4d 0x41

Categories : C#

why Popen can't exec python cmd?
Check your python and your "a.py" script path and make sure they exist! After that try this : import subprocess p = subprocess.Popen(["/usr/bin/python" , "a.py"], stdout=subprocess.PIPE) out, err = p.communicate() good luck!

Categories : Python

subprocess.popen (python) in C
In C, you get the maximum number of options by first calling fork() to create a new process (the eventual subprocess), then one of the exec*() family of functions to execute the subprocess. Both the original process and the new process will run concurrently, so you can exchange (read and/or write data) via pipes or socket pairs. Finally, use e.g. waitpid() in a loop to wait for the new process to exit, and "reap" its exit status. For example: #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> int main(void) { pid_t child, p; int status; /* * Prepare pipes et cetera first. */ /* Fork to create the subprocess. */ child = fork(); if (child == (pid_t)-1) { /* Cannot fork(); usually out of re

Categories : Python

How to control gdb using Python subprocess.Popen?
.communicate waits for a Popen object to finish execution. Since you are trying to talk to gdb while it's running, this will just hang forever. gdb isn't going to exit without any input. Additionally you need to write the newlines yourself to emulate the user hitting enter. what you want to do is write into and read from gdb while it is executing. For this, use p1.stdin.write('break main ') (note the ' ') when sending input, and p1.stdout.readline() when reading output. This applies to the break in the beginning, the args you are sending, and the continues. On sending the arguments and beggining executing, you should also be sure to start gdb. p1.stdin.write('start ' + args1 + ' ') p2.stdin.write('start ' + args2 + ' ') You also want to handle the case where one process terminate

Categories : Python

Python os.popen requires an integer?
No, a "file descriptor" is an integer, not the file object. To go from a file object to a file descroptor, call file.fileno(). To wit: >>> f = open("tmp.txt", "w") >>> help(f.fileno) Help on built-in function fileno: fileno(...) fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). >>> f.fileno() 4 Instead of using that, though, you probably just want to do the following, unless you really need to use the low-level functions for some reason: f = os.popen('cat > out', 'w',1) f.write('hello pipe') f.close()

Categories : Python

select and Pipes trouble in Python
According to the docs, select needs a file descriptor from os.open or similar. So, you should use select.select([pipein], [], []) as your command. Alternatively, you can use epoll if you are on a linux system. poller = epoll.fromfd(pipein) events = poller.poll() for fileno, event in events: if event is select.EPOLLIN: print "We can read from", fileno

Categories : Python

Inconsistent stdout on Python subprocess.popen
I suppose it is the """stuff (which would look nicer as '"', BTW). You are calling Popen() without shell=True, so you should give the parameters as you want them. On a normal egrep call the "" are stripped away by the shell, a step which you don't have here. SO you don't need them here.

Categories : Python

python - subprocess.Popen() synax errors
The problem is that you're trying to run a shell command without the shell. What happens is that you're passing all of those strings—including "|" and everything after is—as arguments to the echo command. Just add shell=True to your call to fix that. However, you almost definitely want to pass the command line as a string, instead of trying to guess at the list that will be joined back up into the string to pass to the shell. Or, even better, don't use the shell, and instead pipe within Python. The docs have a nice section about Replacing shell pipeline (and all kinds of other things) with subprocess code. But in your case, the thing you're trying to pipe is just echo, which is quite silly, since you already have exactly what echo would return, and can just feed it as the input to

Categories : Python

python subprocess pipes stdin without using files
First, use subprocess.Popen - .call is just a shortcut for it, and you'll need to access the Popen instance so you can write to the pipe. Then pass subprocess.PIPE flag as the stdin kwarg. Something like: import subprocess proc = subprocess.Popen('shell command', stdin=subprocess.PIPE) proc.stdin.write("my data") http://docs.python.org/2/library/subprocess.html#subprocess.PIPE

Categories : Python

python subprocess.popen tshark works with some args, but not others
subprocess.Popen by default bypasses CMD.EXE / sh, therefore command line I/O redirections (<, >) will not work. You can get a similar effect like this: tsharkCall = ["tshark", "-i", "-", "-V"] tsharkIn = open("tshark.pcap", "rb") tsharkOut = open("tshark.txt", "wb") tsharkProc = subprocess.Popen(tsharkCall, stdin=tsharkIn, stdout=tsharkOut, executable="C:\Program Files\Wireshark\tshark.exe")

Categories : Python

How to send an argument from one python script to another using subprocess.Popen communicate?
When you do: process.communicate(f) you are writing to the standard input of process; the problem is that the latter program must read the data from its input stream in order to make use of it. You could change file2.py to something like: import sys def c(x): print x for f in sys.stdin: c(f) You seem to be thinking that communicate() allows the parent and child processes to share variable bindings; that's not the case. As written in your question, file2.py would generate an error to the effect that name 'f' is not defined.

Categories : Python

Using subprocess.popen with multiple stdin to configure system : Python 2.7
I haven't used Postgres in ages, but I'm guessing you want to su to postgres, and then run a command that requires postgres' rights. But your run(['sudo', 'su', '-', 'postgres']) will probably just open a shell and wait; run(['createuser'], False, 'testuser') will likely never get run. Instead, I believe you should combine these two commands. See the "-c" option to su. Alternatively, and a little more securely, you could give your source user postgres rights in sudo, to take root out of the equation and make your code a little simpler.

Categories : Python

How to pass utf8 strings properly from python to hunspell via subprocess.Popen?
As Iwan Aucamp suggested in the comments, the solution is to use: hunspell -i UTF-8 ... i.e. make sure that hunspell knows it's getting UTF-8 strings. Once I added that to my code, the results I was getting in the shell (even without the -i flag) and the results I was getting by piping strings to hunspell from Python were the same.

Categories : Python

Timeout within a popen works, but popen inside a timeout doesn't?
In the first block, the timeout is raised in the child, killing it and returning control to the parent. In the second block, the timeout is raised in the parent. The child never gets the signal. See io.c https://github.com/ruby/ruby/blob/trunk/io.c#L6021 and timeout.rb https://github.com/ruby/ruby/blob/trunk/lib/timeout.rb#L51

Categories : Ruby

Python QT QNetworkRequest exits with "(process:3265): GLib-ERROR **: Creating pipes for GWakeup: Too many open files"
Is your condition self.image_reply.error() == Qt.QNetworkReply.NoError always true? If it ts false, deleteLater will not be called. Try to set 'Connection: close' header: image_request.setRawHeader("Connection", "close"); Also try to call self.image_reply.close() manually.

Categories : Python

Trying to send an EOF signal (Ctrl+D) signal using Python via Popen()
EOF isn't really a signal that you can raise, it's a per-channel exceptional condition. (Pressing Ctrl+D to signal end of interactive input is actually a function of the terminal driver. When you press this key combination at the beginning of a new line, the terminal driver tells the OS kernel that there's no further input available on the input stream.) Generally, the correct way to signal EOF on a pipe is to close the write channel. Assuming that you created the Popen object with stdin=PIPE, it looks like you should be able to do this.

Categories : Python

RegExp (in Javascript) minimum length and minimum length after pipes, if pipes are present
var array = "weather|br||flock|red".split('|'); //["weather", "br", "", "flock", "red"] var valid = true; //now iterate array and check if any item is < 4 length for(var i=0; i < array.length; i++){ if(array[i].length < 4 ) valid = false; } console.log(valid);

Categories : Javascript

Can't execute python script from php
Your problem is this: When launching the php script through the console, you are launching php with the permissions of your current user. When a process is executed through opening it in the browser, it will have the permissions of the user of your web-server-process. Your group permissions will have to be 7 no matter what. Either change the python scripts permissions to 777 (read-write-execute for everybody) or change it to 770 and make sure that your web-servers user is inside the group set to the file.

Categories : PHP

Python: Why does this code execute?
This is the output I get: 1 2 2 1 3 0 4 -1 5 -2 6 -3 7 -4 8 -5 9 -6 10 -7 Your question as to why it runs. Your outer most conditional is a while loop, which is true upon the first execution, however it runs right into a nested for loop. When this happens the while, will not be checked until the for loop finishes its first execution (which is why p = -7). What you want is this: p = 2 for i in range(10): if p <= 0: break print i+1 , p p-=1 which gives output: 1 2 2 1

Categories : Python

execute main through if condition in python
Make it an independent function. def run_main(): .... if __name__ == "__main__": run_main() And you can call run_main() from another file.

Categories : Python

Execute python in a php script using shell_exec()
I think kernel not able to find the path for python where it is installed..if you can do echo $PATH..it will show all the paths where to be search a command if given add your python part there and then it may work or you can give absolute path(other than /usr/bin/) see if it works..I need to test it too.

Categories : PHP

Execute python script in localhost
Google App Engine SDK for Python includes a local web server application that simulates the App Engine environment. It allows for instant server script changes by just saving the file and refreshing the browser. The development tutorial is here Once you have your web site working locally, it is easy to deploy it live on Google's App Engine servers.

Categories : Python

Execute .sql schema in psycopg2 in Python
You can just use execute: with self.connection as cursor: cursor.execute(open("schema.sql", "r").read()) though you may want to set psycopg2 to autocommit mode first so you can use the script's own transaction management. It'd be nice if psycopg2 offered a smarter mode where it read the file in a statement-at-a-time and sent it to the DB, but at present there's no such mode as far as I know. It'd need a fairly solid parser to do it correctly when faced with $$ quoting (and its $delimiter$ variant where the deimiter may be any identifier), standard_conforming_strings, nested function bodies, etc. Note that this will not work with: anything containing psql backslash commands COPY .. FROM STDIN ... and therefore won't work with dumps from pg_dump

Categories : Python

How to execute commands through pipe in Python?
Piping is a shell function. Therefore your Popen call needs shell=True on it. Otherwise your | wc is going to be passed to find, which won't know what to do with it (and is probably sending an error to that effect into err... which you're not printing). But why shell out at all? Just do all that stuff in Python (e.g. os.walk to replace find) It'll be easier to read and maintain. Something like: import os, re for dirpath, dirnames, filenames in os.walk(rootpath): for filename in filenames: if filename.endswith(".cc"): with open(os.path.join(dirpath, filename)) as infile: text = infile.read() chars = len(text) lines = sum(1 for x in re.finditer(r" ", text)) lines += not text.endswith(" ") # count last

Categories : Python

How to execute awk command by python code
While I agree that this is actually best done in Python, rather than invoking awk. If you really need to do this, then the actual error is with your awk. #!/usr/bin/env python import subprocess as sp args = ["awk", r'{OFS=" "; print $2,$4,$5,$6}', "B3LYPD.txt"] p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE ) print(p.readline()) # will give you the first line of the awk output Edit: Fixed missing quote.

Categories : Python

Python: rasing from except causes finally to execute?
finally is executed no matter the try block succeeds or the except block is run due to exceptions! even if your except block raises an exception the new exception will be handled by another try catch handler but after executing the finally block, instead of forming a recursive loop: try: try: [...] except: raise Exception([...]) #this is line number xyz finally: [code] except: [...] #this code will be running after line number xyz

Categories : Python

crontab doesn't execute my python script
First, you have an odd indentation in the line with if __name__ ==... - guess you should check it in your script. Then, make sure with what current directory your script runs, AFAIK it is your $HOME - this is where the file would appear.

Categories : Python

Execute R script with python subprocess.call
Using commandArgs like this: args <- commandArgs(trailingOnly = TRUE) arg1 <- args[1] arg2 <- args[2] [...your code...] Also make sure that the Rscript executable is in your PATH.

Categories : Python

crontab: python script being run but does not execute OS Commands
Two things: Your cd will set the directory for that subprocess, which immediately exits: subprocess.call(["cd", "/home/atweb/Documents/opengrok"]) In other words, it's a wasted step. The next subprocess doesn't know anything about the previous one's environment: subprocess.call(["./stop_website"]) ...so it won't be able to run. If you want all of your programs to run in that directory, use: os.chdir("/home/atweb/Documents/opengrok") before any of the subprocess.call() lines.

Categories : Python

Execute python script using urllib2 from PHP behind Proxy
You could try passing explicit proxy settings to your Python script to see if that clears up the problem for you. I recently wrote a script that allows you to set proxy settings with command line arguments that might be useful for this case. The important parts of the script are below: # Import the required libraries from urllib import urlencode from urllib2 import Request, urlopen, URLError, ProxyHandler, build_opener, install_opener import argparse # Set up our argument parser parser = argparse.ArgumentParser(description='Does stuff through a proxy') parser.add_argument('webAddr', type=str, help='Web address of target server') parser.add_argument('--proxServ', metavar='SERV', type=str, help='Web address of proxy server, i.e. http://proxy.server.com:80') parser.add_argument('--proxType'

Categories : PHP

Execute Shell Script from python with variable
Like this ? subprocess.call(['test.sh', str(domid)]) Documentation is available on the python website

Categories : Python

In Python, how do you execute objects that are functions from a list?
Make all of them lists and then iterate over the list executing each in turn. for actionVal,actionDesc,actionFunctions in validActions: if ctx["newAction"] == actionVal: for actionFunction in actionFunctions: actionFunction()

Categories : Python

How to execute code when a Python script is closed out?
import MySQLdb con = MySQLdb.connect(...) cursor = con.cursor() try: # do stuff with your DB finally: con.close() The finally clause is executed on success as well as on error (exception). If you hit Ctrl-C, you get a KeyboardInterrupt exception.

Categories : Python

Execute and wait for results C program and Python script
Use subprocess module. import os import signal import subprocess import sys params = [...] for param for params: proc = subprocess.Popen(['/path/to/CProg', param.., param..]) subprocess.call([sys.executable, 'B.py', param.., param...]) os.kill(proc.pid, signal.SIGINT) proc.wait()

Categories : Python

Use value from javascript on html page to execute python script
Here is a simple Python script that pipes the output of a locally executed command (dir on a Windows computer in this case) via a web request (using the excellent web.py library): import web from subprocess import check_output urls = ( '/', 'index' ) app = web.application(urls, globals()) class index: def GET(self): return '<pre>'+check_output('dir', shell=True)+'</pre>' if __name__ == "__main__": app.run()

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.