w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Subprocess module from python fails to run bash commands like " | "
This: echo Hello world | cut -d' ' -f1 … is not actually a command, it's a fragment of shell script. So you need to have the shell execute it. You can do this just by adding shell=True to the Popen constructor. The documentation explains how this works. It also explains better ways to do the same thing without the shell. For example: p1 = Popen(['echo', 'Hello', 'world'], stdout=PIPE) p2 = Popen(['cut', "-d' '", '-f1'], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() test = p2.communicate()[0] Meanwhile, you almost never want to use split on a command line—and in fact, your example shows exactly why you don't want to: >>> cmd = "echo Hello world | cut -d' ' -f1" >>> cmd.split() ['echo', 'Hello', 'world', '|', 'cut', "-d'", "'", '-f1'] Notice that it spl

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

Executing code when my form is closed
I think that what you need is not access to the close button, but rather access to the event which is fired when the form is closed. Taken from this previous SO post, what you might need is something like so: void FormClosed(object sender, FormClosedEventArgs e) { // do something useful }

Categories : C#

Python thread timer, not executing or executing instantly
You lost all the indentation in your code snippet, so it's hard to be sure what you did. The most obvious problem is responseTimer.start. That merely retrieves the start method of your responseTimer object. You need to call that method to start the timer; i.e., do responseTimer.start(). Then it will produce the output you expected, with a delay of about 2 seconds before the final "timeout!" is printed.

Categories : Python

Code after showDialog is not execute when the modal window is closed by the other thread -- C#
Unless you have a long running or slow operation, there is no reason why you should complicate your life with a separate thread. Just show your dialog form in modal mode and proceed when the user has input the required data.

Categories : C#

Node.js console gets closed immediately after i execute the program from Visual Studio 2012 in Windows 8
Instead of directly executing node app.js from Visual Studio, you could instead call a batch file: wait.bat app.js Which inside of wait.bat it simply: node %1 pause press [enter] or, you could do this on one line, or wrap it in a module or a function: require('readline') .createInterface(process.stdin, process.stdout) .question("Press [Enter] to exit...", function(){ process.exit(); }); It's using an currently marked as "unstable" module of Node to read line input from stdin. It ignores the input though and then closes the process using the exit function.

Categories : Javascript

ActiveRecord execute SQL need to close connection? DEPRECATION WARNING: Database connections will not be closed automatically
In This case You need to close your connection manually. After running your script, you can close it Manually like this. after do ActiveRecord::Base.connection.close end

Categories : Ruby On Rails

executing current line then search for next and execute
I am not sure if you really need a function for it. way 1 can you simply do : :%!sh to execute whole buffer once? way 2 For example, if you have some line in your buffer not starting with mysql, and you don't want to execute them, you could do: :g/^mysql/.!sh way 3 if you really want to do it one by one, like you described in your question, execute and move to next mysql, execute, you could do it as macro: /^mysql<cr> "search the pattern gg "cursor back to top qq "start recording to q !!sh<cr> "run first line as shell command, take output back n "next command line (with pattern) q "stop recording then 500@q if you have 500 lines to be executed.

Categories : Vim

mysqli_stmt::execute() returning false and statement not executing
Either set mysqli into Exception mode mysqli_report(MYSQLI_REPORT_ALL); or always check the result of every mysqli operation and throw mysqli error manually: $result = $stmt->execute(); if (!$result) { throw new Exception($mysqli->error"); } this is the only way to know what's wrong with your execute(); I have found that the SQL syntax apparently needs quotation marks around the fields for the VALUE Of course it is wrong. SQL syntax apparently needs quotation marks around strings only.

Categories : PHP

Execute SQL task with T-SQL sp or Executing the Sp from SSMS ,which one is performance wise better?
You could also invoke your stored procedure using a .NET library, calling it from the command line (OSQL, SQLCMD, etc), starting it in a SQL Agent job but the calling program doesn't matter in the slightest. Ultimately, the SQL Server Database Engine will receive the request that you'd like to run a stored procedure and for the same parameters, it's going to use the same query plan regardless of the caller. If you are observing differences, check out Erland's article: Slow in the application, Fast in SSMS So, your real question seems to be about loading a CSV. Your stored procedure approach should still give you the same performance regardless of how it's started. As long as you have a fixed CSV file (you aren't trying to write a generic import-anything), you might get better performan

Categories : Sql Server

Why doesn`t the finish statement execute after the yield key word executing in Tornado
If you are using yield gen.Task() you need to add asnyc decorators to your method: from tornado import gen, web @web.asynchronous @gen.engine def get(self, param): # your get method

Categories : Misc

working in python console while executing a boost::python module
You have two options: start python with the -i flag, that will cause to drop it to the interactive interperter instead of exiting from the main thread start an interactive session manually: import code code.interact() The second option is particularily useful if you want to run the interactive session in it's own thread, as some libraries (like PyQt/PySide) don't like it when they arn't started from the main thread: from code import interact from threading import Thread Thread(target=interact, kwargs={'local': globals()}).start() ... # start some mainloop which will block the main thread Passing local=globals() to interact is necessary so that you have access to the scope of the module, otherwise the interpreter session would only have access to the content of the thread's scope.

Categories : Python

Python 2: SMTPServerDisconnected: Connection unexpectedly closed
Most probably the gmail server rejected the connection after the data command (very nasty of them to do so at this stage :). The actual message is most probably this one: retcode (421); Msg: 4.7.0 [ip.octets.listed.here 15] Our system has detected an unusual rate of 4.7.0 unsolicited mail originating from your IP address. To protect our 4.7.0 users from spam, mail sent from your IP address has been temporarily 4.7.0 rate limited. Please visit 4.7.0 https://support.google.com/mail/answer/81126 to review our Bulk Email 4.7.0 Senders Guidelines. qa9si9093954wjc.138 - gsmtp How do I know that? Because I've tried it :) with the s.set_debuglevel(1), which prints the SMTP conversation and you can see firsthand what's the issue. You've got two options here: Cont

Categories : Python

Python Redis connection should be closed on every request? (flask)
By default redis-py uses connection pooling. The github wiki says: Behind the scenes, redis-py uses a connection pool to manage connections to a Redis server. By default, each Redis instance you create will in turn create its own connection pool. This means that for most applications and assuming your redis server is on the same computer as your flask app, its unlikely that "opening a connection" for each request is going to cause any performance issues. The creator of Redis Py has suggested this approach: a. create a global redis client instance and have your code use that. b. create a global connection pool and pass that to various redis instances throughout your code. Additionally, if you have a lot of instructions to execute at any one time then it may be worth having

Categories : Python

Finalizing a Cursor that has not been deactivated or closed or database not closed error
When you are done with the cursor, you need to call Cursor.close(). Leaving it not closed leads to memory leaks. E.g.: Cursor cursor = null; try { cursor = getContentResolver().query(myUri, MY_PROJECTION, null, null, null); if (cursor != null && cursor.moveToFirst()) { // moar code } } finally { if (cursor != null) { cursor.close(); } }

Categories : Android

Run a python socket server and if closed remotely start it listening again
The way you usually program a threaded socket server is: call accept() in a loop spawn a new thread to handle the new connection A very minimal example would be somethig like this: import socket import threading import time server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('0.0.0.0', 9999)) server.listen(1) def handle(conn): conn.send(b'hello') time.sleep(1) # do some "heavy" work conn.close() while True: print('listening...') conn, addr = server.accept() print('handling connection from %s' % (addr,)) threading.Thread(target=handle, args=(conn,)).start() You're spawning new threads in which you create your listening socket, then accept and handle your connection. And while socketIsOpen is True your programm will be using a lot of

Categories : Python

Application gets closed when terminal is closed, how to stop this?
Use nohup to prevent child processes from being killed when the terminal closes. spawn nohup /usr/bin/firefox https://www.google.com/ I assume there's more to the script, since there's no need to use Expect just to start firefox.

Categories : Python

Filter by "begins with" in R
Get the data: test <- data.frame(Code = c("A111", "B111", "C111", "D111", "E111", "A222", "B222", "C222", "D222", "E222" ), Value = c(5L, 10L, 15L, 20L, 25L, 30L, 35L, 45L, 55L, 60L),stringsAsFactors=FALSE) Make the grouping variable for the codes using the first letter (fl): fl <- substr(test$Code,1,1) groups <- ifelse(fl %in% c("A","B"), 1, ifelse(fl %in% c("C","D"), 2, 3)) Calculate a weight using ave to calculate the sum within each group. test$Weight <- test$Value / ave(test$Value,groups,FUN=sum) test Code Value Weight 1 A111 5 0.0625000 2 B111 10 0.1250000 3 C111 15 0.1111111 4 D111 20 0.1481481 5 E111 25 0.2941176 6 A222 30 0.3750000 7 B222 35 0.4375000 8 C222 45 0.3333333 9 D222 55 0.4074074 10 E222

Categories : R

Python script executing SQL on Synology NAS
you can install a mysql connector from official mysql source : http://dev.mysql.com/doc/connector-python/en/index.html. bye

Categories : Python

Executing shell command from python
You can call a subprocess as if you were in the shell by using Popen() with the argument shell=True: subprocess.Popen("nohup ./op.o > myout.txt &", shell=True)

Categories : Python

executing perl script from python
Your Perl script is wrong: You read the path from STDIN, not from the command line arguments. You do not remove the newline after reading a line. You would be looking for "foo " instead of "foo". You have no error checking whatsoever. You do not load the Data::Dumper module. And are you sure that you really want to execute the file at $path as Perl code? Cleaned up, I'd write the Perl script as perl -MData::Dumper -do $ARGV[0];' -e'print Dumper \%some_global' input-file.pl >output Or as use strict; use warnings; use Data::Dumper do $ARGV[0]; open my $fh, ">", "output" or die "Can't open output: $!"; print { $fh } Dumper \%some_global; If you really want the filename from STDIN: use strict; use warnings; use Data::Dumper; chomp(my $path = <STDIN>); do $p

Categories : Python

Executing a set of codes when python GUI is clicked
Use the command option of a Button: from Tkinter import Tk, Button root = Tk() def func(): '''Place code to convert files in here''' print "Button has been pushed" Button(text="Push me", command=func).grid() root.mainloop() func will only run when the button is pressed.

Categories : Python

Executing an Excel macro from Python
I've never done this with EnsureDispatch, but here's how you do it with Dispatch from win32com.client import Dispatch xlApp = Dispatch('Excel.Application') result = xlApp.Run("<macro name here>",<the macro variables go here -seperate each one with a comma>) # for example: #result = xlApp.Run("myMacro", "foo","bar") #and make sure you close the xl xlApp.Quit() oh and I'm aslo on python 2.7, (but I doubt it will matter as the dependency is win32)

Categories : Python

Executing a python file from PHP - Linux
This is most likely a permission issue. Try echo exec("whoami"); This will let you know who php is running as. Then you need to verify this user can run the python script. If the file was not created by the same daemon that runs python, you will most likely be denied permission. Update This will let you know who owns all the files you are working with. The file being written to needs to be writable by the user that is running python. If you are running python from ssh, that is most likely not the same user as when you run python from exec. echo exec('whoami') . "<br>"; echo exec("ls -l test.txt") . "<br>"; echo exec("ls -l somefile.py") . "<br>"; Update 2 Because I constantly forget this exists. passthru('python somefile.py 1 2>&1'); This will e

Categories : PHP

What does gsutil cp do before it begins transferring?
Depending on the arguments you use, it will check for existing files on the destination, calculate md5 checksums for source and destination files. Look and see if an upload needs resuming, calculate md5 checksums for file parts and so on.

Categories : Misc

error if "else" begins with a new php block
There's nothing weird per se, it's because you're in a separate code block, that's the simplest way to put it. Nothing is open at the time of you "Leaving PHP", so when you go back into it there is no context. Consider your code like this (of course consider it as pseudo-code just to emphasise the point): if (isset($_SESSION["user_id"])) { // .... }; else { // .... } Breaking in/out of PHP can be tricky at times, and managing it like you want to in your first example doesn't really make very much sense. You might want to consider using this, which would put your transition to the else block on a single line anyway: <?php if (isset($_SESSION["user_id"])): ?> <h2>Welcome, <?php echo $_SESSION["user_id"]; ?></h2> <?php else: ?> <form acti

Categories : PHP

Executing Fabric python code on windows 7
Fabric requires Python version 2.5 or 2.6. Fabric has not yet been tested on Python 3.x and is thus likely to be incompatible with that line of development. It's not so simple to install Fabric on Windows, because it uses some specific C libs that needs to be compiled. Try next in Windows: pip install fabric # Failed! easy_install fabric # Failed again! But if you don't want to install Visual Studio or Cygwin and compile the C code so I will consider another way, more simple. As I have figured out, Fabric needs next Python libs to be installed on Windows: PyCrypto PyWin32 Both requires compilation OR may be installed from the pre-built binary packages (my choice!): PyCrypto: click here PyWin32: click here Download and install these two and you will be finally able to do: pip inst

Categories : Windows

import module without executing whole script python
If the problem is arising from executing the LogInPage during the import... you can protect the code in LogInPage. Keep those codes in if __name__ == '__main__: block from being executed by import statements.

Categories : Python

Executing Tkinter Code Successfully (Python 2.7)
It appears that you have some indentation issues. Python isn't free form, so you need to pay attention to indentation: from Tkinter import * class App(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): self.entryLabel = Label(self, text="Please enter a list of numbers (no commas):") self.entryLabel.grid(row=0, column=0, columnspan=2) self.listEntry = Entry(self) self.listEntry.grid(row=0, column=2, sticky=E) self.entryLabel = Label(self, text="Please enter an index value:") self.entryLabel.grid(row=1, column=0, columnspan=2, sticky=E) self.indexEntry = Entry(self) self.indexEntry.grid(row=1, column=2) self.

Categories : Python

Python - When executing program via CMD, it just closes after the second input
This has to do with how Windows handles the execution. The default is to close right away after the program has terminated. There may be a setting to fix this, but a quick solution is to open up Command Prompt, cd to the direction, and execute your script directly.

Categories : Python

Python Print Output Executing Out of Order
You're not closing the file when you do this: file.close You're just referencing the close method as a value. What you wanted was to call the close method: file.close() Eventually, the file gets garbage-collected, at which point all of its buffered data gets flushed. But meanwhile, you've opened the same file elsewhere and appended new data to it. On many platforms, your left-over buffers would end up overwriting the later-appended data, instead of getting added after them, making this even harder to debug. You got lucky here. :) If you ran this code through a linter, it would have warned you. With pylint, I get "W0104: Statement seems to have no effect". However, note that it can't possibly catch all such errors. For example: import random r = random.random Here, you're setti

Categories : Python

Wordpress: Different template when pagination begins
You need to make a different page template as your need. You can check official wordpress doc to get started. Wordpress Page Template Reference: http://codex.wordpress.org/Page_Templates

Categories : PHP

GAE: How to build a query where a string begins with a value
You can't do searches like that with the datastore API. You can either store an additional lower-case version of the field, or use the full-text search API which is meant for this sort of thing.

Categories : Python

Regex Include/Except, Begins/Ends
String regex = "[01]*"; //all binary Strings including empty string, * == 0 or more String regex = "[01]+"; //all binary Strings except empty String, + == 1 or more String regex = "^1(?:.*1)?$"; // a string that begins and ends with 1. (?:exp) says group, but do not capture ^ beings with $ ends with ? 0 or 1 (?:.*1)? 0 or 1 of any series of characters ending in 1

Categories : Java

Emacs Org Mode: Executing simple python code
There are two ways of getting the result of a source block - output and value. You mixed them up, hence the troubles. First block is fine. To fix the second block: #+begin_src python :results value return 1+1 #+end_src To fix the third block: #+begin_src python :results output print 1+1 #+end_src When output mode is value you must return. Just putting it there like you did with 1+1 won't do. In the third one you want the result to be printed output, but your default session setting is value(mine defaults to output btw). And this bit about org-confirm-babel-evaluate is kind of irrelevant to the question. I just have it set to nil.

Categories : Python

How can I find the currently executing script file and path in python?
In case __file__ is not set, you can get the directory via import sys, os script = os.path.abspath(sys.argv[0] or 'unknown script') directory = os.path.dirname(script))

Categories : PHP

Dynamically reading in a python file and executing it safely
You can consider following method class _DynamicModule(object): def __init__(self, name): self._name = name def load(self, code): execdict = {'__builtins__': __builtins__} exec compile(code, '<string>', 'exec') in execdict for key in execdict: if not key.startswith('_'): if not isinstance(execdict[key], str): execdict[key].__module__ = self._name setattr(self, key, execdict[key]) return self import sys sys.modules['dummy_modules'] = _DynamicModule('dummy_modules').load('print ("!")') This still has pretty big security concerns.

Categories : Python

Executing multiple .py python scripts in same directory in terminal?
Assuming bash: for i in x y z; do python ~/abc/$i.py & done This loop iterates over the strings "x", "y" and "z". each iteration the variable $i is another one of them. So in the first iteration, $i is x, so ~/abc/$i.py is ~/abc/x.py. The second iteration is the same, only with y, and in the third $i is x. So bash actually do python ~/abc/x.py & python ~/abc/y.py & python ~/abc/z.py & Which is what you asked for. The & makes it run in the background. You can do this for any command you invoke.

Categories : Python

capturing keyboard interrupts during while executing Python scripts
I assume that the problem is that Python parent process receives SIGINT from Ctrl+C and quits with unhandled exception, but the child ignores signal and keeps running. That is the only scenario I was able to reproduce. Actual problem may differ. Catching exception and killing subprocess explicitly with SIGKILL may work. Instead of subprocess.call: proc = subprocess.Popen(['/bin/bash', scriptfile.name]) try: proc.wait() except: proc.kill() raise

Categories : Python

Executing shell program in Python without printing to screen
If subprocess.check_ouput is not working for you, use a Popen object and a PIPE to capture the program's output in Python. prog = subprocess.Popen('./myprog', shell=True, stdout=subprocess.PIPE) output = prog.communicate()[0] the .communicate() method will wait for a program to finish execution and then return a tuple of (stdout, stderr) which is why you'll want to take the [0] of that. If you also want to capture stderr then add stderr=subprocess.PIPE to the creation of the Popen object. If you wish to capture the output of prog while it is running instead of waiting for it to finish, you can call line = prog.stdout.readline() to read one line at a time. Note that this will hang if there are no lines available until there is one.

Categories : Python



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