w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Redirect output of a .bat file run by a python script to GUI, and making that script into EXE
You could use the subprocess module to call your script Example calling the 'ls' command on Linux: >>> from subprocess import call >>> call(['ls', '-l']) total 0 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file1 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file2 -rw-rw-r-- 1 user group 0 Jun 17 18:37 file3 0

Categories : Python

Invoke python script from another python script and set execution directory of the executed script
You could use cwd parameter, to run scriptB in its directory: import os from subprocess import check_call check_call([scriptB], cwd=os.path.dirname(scriptB))

Categories : Python

how to pass variable from python to shell script when shell script is getting called inside python script
You can: Step through the list, and then call mail.sh once for each file. This is the most reliable way. Convert the items in the list to a space delimited string, and then pass it in to mail.sh (assuming mail.sh is setup correctly, it should accept multiple arguments). What you cannot do is pass ['a.txt','b.txt','c.txt'] wholesale to the script.

Categories : Python

What do I do to make a python script that can run from any directory: the script file doesn’t have to be in the same directory as the .csv files?
Assuming you mean to include a fixed CSV file with your code, store an absolute path based on the script path: HERE = os.path.dirname(os.path.abspath(__file__)) csv_filename = open(os.path.join(HERE, 'somefile.csv') __file__ is the filename of the current module or script, os.path.dirname(__file__) is the directory the module resides in. For scripts, __file__ can be a relative pathname, so we use os.path.abspath() to turn that into an absolute path. This means you can run your script from anywhere. If you meant to make your script work with arbitrary CSV input files, use command line options: import argparse if __name__ == '__main__': parser = argparse.ArgumentParser('CSV importer') parser.add_argument('csvfile', type=argparse.FileType('w'), default

Categories : Python

On Mac, how to create a drag & drop app for a python script where the script name rather than Python shows in the MenuBar (etc.)?
I have an answer to my question, but I am hoping that someone can come up with something less complex. The solution I came up with was a Python script to create an AppleScript (ugh!), compile it into a bundle and then modify the bundle to change the allowed file extension(s), the icon and so on. I did not find a way to get drag-and-drop working when starting a wxpython script, without an AppleScript (or using py2app) and I could not get the AppleScript to work in a bundle I created, I had to use osacompile to create the bundle for me. I like better the approach here or here, where one creates the plist file "by hand" rather than than modify an externally created one as I do here, but the script below does do the job. #!/usr/bin/env python '''This script creates an AppleScript app to

Categories : Python

Jenkins runs imported python script before main python script
The child process flushes its output buffers on exit but the prints from the parent are still in the parent's buffer. The solution is to flush the parent buffers before running the child: print("Starting script...") sys.stdout.flush() build.run()

Categories : Python

How to feed in an answer to input in script in Python
A little unorthodox, but you can monkey-patch sys.stdin: # We're going to monkey-patch stdin import sys from cStringIO import StringIO old = sys.stdin sys.stdin = StringIO('hello') # Now read from stdin result = raw_input('foo') # And replace the regular stdin sys.stdin = old This will work as if you typed 'hello' as the input for raw_input. Of course, rather than calling raw_input yourself, you'd be calling your foo function. I think if I were going to do this more than once, I'd use a context manager to be certain I undo the monkey patch: import sys from cStringIO import StringIO class PatchStdin(object): def __init__(self, value): self._value = value self._stdin = sys.stdin def __enter__(self): # Monkey-patch stdin sys.stdin = StringIO(self

Categories : Python

Python script saving over input variables
t0 = temp doesn't actually perform a copy. It makes the names t0 and temp both refer to the same array. You probably want t0 = temp.copy() which makes a new, independent array.

Categories : Python

Script not posting input to PHP server script.
Your dataString is incorrect, you forgot a '&' between vars : var dataString = 'mac=' + mac + '&store=' + store; Plus there is no need for a string, just pass an object, jQuery will do the rest : $.ajax({ type: 'POST', url: 'ajax/subscribe.php', data : {mac: mac, store: store}, etc...

Categories : PHP

sys module giving different output when running Python script through IDLE and by double-clicking the script
print os.path.dirname(sys.executable) is what you should use. When you click it it is probably running through python.exe so you are removing the extra char from the w.

Categories : Python

how to call a python script inside another python script where both in the same directory?
In script1.py place this: def main(): do something if __name__ == "__main__": main() In script2.py: import script1 if condition: script1.main()

Categories : Python

Cron not running Python script is script not in home folder
cron is running crontab(5) entries from the home directory of the user. You need to change appropriately the directory i.e. to call the chdir(2) syscall (either thru the cd shell builtin, or inside your python script using os.chdir). You should query the current directory (using getcwd(3), or the pwd command, or the os.getcwd in Python) in your script. Also check your PATH if running commands.

Categories : Python

dump files from bash script in different directory from where python script ran it
You should change directory within the same command: cmd = "/path/to/executable/executable" outputdir = "/path/to/output/" subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True)

Categories : Python

How do scan a script for return values from a upper script in python?
Don't invoke a Python script from a Python script by using system, which spawns a whole other interpreter. Just import it. Like this: import ToBuildOrNot needsBuild = ToBuildOrNot.run() # or whatever you call your top-level function Since ToBuildOrNot.py is a script now, make sure the "main" function is protected so it doesn't execute automatically on import. Most people do it this way in Python: What does <if __name__=="__main__":> do?

Categories : Python

How to write a bash script that can parse through an XML file as input and remove certain elements from the file
Perhaps you could use php like this: running php script (php function) in linux bash And then you something like domdocument(http://php.net/manual/en/class.domdocument.php) to read and the right the xml. Of course this is assumes you have php installed.

Categories : Xml

Create output file names based on input file name with autonumbers shell script linux
VAR="INPUTFILENAME" # One solution this does not use the VAR: touch INPUTFILENAME{1,2,3,4,5,6,7,8,9,10} # Another for i in `seq 1 20` ; do touch "${VAR}${i}" done And there are several other ways.

Categories : Linux

Script to call either from file or user input
Try using this if [ $# -eq 0 ]; then cat > temporary.txt; sed '/^$/d' <temporary.txt else cat $@ | sed '/^$/d' fi A space is needed between [ and $@ and your usage of $@ is not good. $@ represents all arguments and -eq is used to compare numeric values.

Categories : Shell

Execute script after load input file
I didnt test it, but this might work: jQuery(document).ready(function () { $("#logo2").change(function(){ jQuery('#form_up').ajaxSubmit({ dataType: 'json', success: bol }); }); }); Check the Plugin API if this dont work, I just quick checked it, and saw there is a ajaxSubmit...

Categories : Javascript

Running a script in IPython with input from a file
One solution would be to execute the script this way: In [1]: !python my_script.py < datafile Obviously, this works around the run command, but it allows you to execute your script from within IPython.

Categories : Python

How do I accept user input on command line for python script instead of prompt
Replace src = input('Enter Path to src: ') with: import sys src = sys.argv[1] Ref: http://docs.python.org/2/library/sys.html If your needs are more complex than you admit, you could use an argument-parsing library like optparse (deprecated since 2.7), argparse (new in 2.7 and 3.2) or getopt. Ref: Command Line Arguments In Python Here is an example of using argparse with required source and destination parameters: #! /usr/bin/python import argparse import shutil parser = argparse.ArgumentParser(description="Copy a file") parser.add_argument('src', metavar="SOURCE", help="Source filename") parser.add_argument('dst', metavar="DESTINATION", help="Destination filename") args = parser.parse_args() shutil.copyfile(args.src, args.dst) Run this program with -h to see the help message.

Categories : Python

ImportError when calling python script via a shell script
I had a similar problem. It turned out that in my bash script I was running the Python script with a different version of Python than I was on the command line (my env was set up with virtualenv on Python 2.7 but I was calling the script with Python3 from the bash script). There is nothing in your snippets indicating this is the case but it is worth checking to make sure that the Python versions match up.

Categories : Python

How run a Python script from another script and get resulting global dict?
Importing a module executes the code at the top level, and that module's "global" namespace gets imported as the name of the module james@bodacious:~$cat test.py def func(): pass myname = "michael caine" print "hello, %s" % myname james@bodacious:~$python Python 2.7.5 (default, Jul 12 2013, 18:42:21) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import test hello, michael caine >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'func', 'myname'] >>> if the code you want to be run is at the top level of the file, just importing the module will execute the code and give you access to its "global" namespace all in one convenient package.

Categories : Python

error with global name when running a script from another script - python
This is a pretty interesting problem. First a quick workaround, you can provide dictionaries to use as the local and global namespace when calling execfile(), using an empty dictionary for globals works fine: # test_fun1.py a = 1 def test1(): print a execfile('test_fun2.py', {}) test1() Alternatively, if you want the code to execute within the global scope of your module you can use globals() instead of {}. Now on to why this isn't working... from the documentation on execfile(): If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. Here "both dictionaries" is referring to the optional globals and locals arguments to execfile(). In this case "the environment where execfile() is called" is the local scope of the fun

Categories : Python

Using a file input as stdin for a shell script does not work
What do you need the <&1 for? Remove it, and it works. while read CMD; do ./test.sh < input.txt BEGIN get_start END get_stop END get_uknown_command END

Categories : Linux

Chrome Extensions: Pass data from popup to another script file before the script is injected
There are several ways to accomplish this. One would be: function click(e) { var elementIDs = { email: document.getElementById("emailID").value, company: document.getElementById("nameID").value }; chrome.tabs.executeScript({ code: 'window.elementIDs='+JSON.stringify(elementIDs) }, function() { chrome.tabs.executeScript({file: "ScriptA.js"}); }); window.close(); } This way, ScriptA will be able to access the values in window.elementIDs. This will work because content scripts from the same extension on the same page will share the execution environment, and the chaining of the calls to chrome.tabs.executeScript ensures that the script defining the global variable has run before ScriptA is run.

Categories : Javascript

In Embedded Octave C++ how do I execute a script file? ("error: invalid call to script")
You should be using the function source_file() rather than eval_string(). Take a look into the parser.h file which unfortunately doesn't have a lot of comments. The names are quite self-explanatory so you shouldn't have a lot of problems. Also, you're pretty much trying to reimplement Octave's source function. If you really want to implement it again, look into the oct-parse.cc file (generated during the build process with flex and bison).

Categories : C++

malware code insert script to my .js .php and include file. help me to decode script
If you crawl through the code and methodically replace the junk identifier names, it makes a lot more sense. Most of the code and identifiers are just there to obscure, and a lot of the rest of it just looks like boilerplate code for browser-compatible ways to do things like attach events. It also makes a pretty big deal of checking that you're on Windows, for some reason, but that doesn't change the payload that's eventually delivered. The piece that deploys the payload to the page is here: var newElement = window[_document][_createElement](_div); newElement[_innerHTML] = decodeString(key, payload); newElement[_style][_display] = _none; window[_document][_body][_appendChild](newElement); The payload decrypts as: <iframe src='http://teenee.&lt;OBFUSCATED&gt

Categories : Misc

Executing a script within a script but continuing on error(s) and saving them to file
errors = open('errors.txt', 'w') try: execfile("script.py") except Exception as e: errors.write(e) try: execfile("other.py") except Exception as e: errors.write(e) errors.close()

Categories : Python

Script to check if it is a directory or file and then process the rest of the script
Your usage of else if is incorrect, it should be elif if [ -f "$i" ]; then echo "this is a file and I'll run a script if it is a file" elif [ -d "$i" ]; then echo "this is a dir and I'll run a script if it is a directory" fi

Categories : Bash

Convert VBA Script to run as VBS file windows or some type of script on a linux box
At Ken's proding, I was able to plod through my error with google's help. Thanks Ken. Here is my reworked code that works as a vbs script Option Explicit Public Sub IE_Check() Dim i Dim g Dim x Dim IE Dim objElement Dim objElement2 Dim Colobj1 Dim Colobj2 Dim Colobj3 Dim FindText1 Dim FindText2 Dim FindText3 Dim TTime Dim dteWait Dim fso Set fso = CreateObject("Scripting.FileSystemObject") ' Declare a TextStream. Dim stream ' Create a TextStream. Set stream = fso.OpenTextFile("C:log.txt", 8, True) TTime = Time Set IE = CreateObject("InternetExplorer.Application") IE.Visible = True IE.Navigate "http://yahoo.com" While IE.ReadyState < 4 FindText1 = 0 Wend FindText1 = InStr(1, IE.Document.body.innerhtml, "Internet Explorer cannot display the webpage") If FindText1

Categories : Vba

Shell Script that performs different functions based on input from file
Use read to input the lines. Do a case statement on their prefix: { while read DATA; do case "$DATA" in #*) ... switch function ...;; *) eval "$FUNCTION";; esac done } <inputfile Dependent on your problem you might want to experiment with setting $IFS before reading and read multiple variables in 1 go.

Categories : Linux

How to get a python script to listen for inputs from another script
I would use a socket connection. Essentially you are writing a very simple server that only takes one connection at a time import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("localhost", 9988)) s.listen(1) while True: conn, addr = s.accept() data = conn.recv(1024) conn.close() my_function_that_handles_data(data) s.accept() is a blocking call. It waits for a connection. Then you do a read on the connection. In this case we are assuming the length of the parameters are only 1024 bytes. Then we do something with the data we received from the socket and wait for another connection. The client could look like this: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", 9988)) s.sendall('My parameters that I wan

Categories : Python

When running Python's pdb as a script, how do I autostart the script?
that's probably not the way to do to it. you should modify/extend the existing pdb.py. the code looks like this: while True: try: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print "The program finished and will be restarted" except: traceback.print_exc() print "Uncaught exception. Entering post mortem debugging" print "Running 'cont' or 'step' will restart the program" t = sys.exc_info()[2] pdb.interaction(None, t) print "Post mortem debugger finished. The "+mainpyfile+" will be restarted" it looks like you could replace `pdb._runscript(mainpyfile)' with something like runpy.run_module(sys.argv[0], run_name="__main__", alter_sys=True) (from PEP 338). not a complete solutio

Categories : Python

How to return a value from a shell script in a python script
use Subprocess.check_output instead of Subprocess.call. Subprocess.call returns return code of that script. Subprocess.check_output returns byte stream of script output. Subprocess.check_output on python 3.3 doc site

Categories : Python

Conversion of shell script to python script
It looks like you're after a templating engine, but if you wanted a straight forward, no thrills, built into the standard library, here's an example using string.Template: from string import Template with open('a.html') as fin: template = Template(fin.read()) print template.substitute(name='Bob') # <head>Bob</head> I thoroughly recommend you read the docs especially regarding escaping identifier names and using safe_substitute and such...

Categories : Python

Bash script to wait for gnome-terminal to finish before continuing script, only works for first instance of script
#!/bin/bash date bash -c "sleep 7" & bash -c "sleep 5" & wait date As you can see while running this script, both sleep commands will run in parallel, but main thread stalls, while they are running. Sat. Jule 27 01:11:49 2013 Sat. Jule 27 01:11:56 2013 Replace sleep 7 with expect launchneuron.exp and sleep 5 with expect launchmpj.exp and add your plot commands after calling "wait": echo "Simulation Complete" ...(your code to plot results)

Categories : Bash

PowerShell - script 1 calls script 2 - how to return value from script 2 to script 1
You could make use of ProcessStartInfo and Process which would allow you to read the StandardOutput. Here's an example of what you might do: $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = "powershell.exe" $startInfo.Arguments = "C:scriptscript2.ps1" $startInfo.RedirectStandardOutput = $true $startInfo.UseShellExecute = $false $startInfo.CreateNoWindow = $false $startInfo.Username = "DOMAINUsername" $startInfo.Password = $password $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $standardOut = $process.StandardOutput.ReadToEnd() $process.WaitForExit() # $standardOut should contain the results of "C:scriptscript2.ps1" $standardOut

Categories : Powershell

How to runCommand() of a bash script with redirected input from file in Mozilla Rhino?
You need to pass the input stream in as the input property of an object. var inputStream = new java.io.FileInputStream("fileInput.txt"); runCommand("somescript.sh", { input: inputStream }); If input is not an InputStream it will be converted to a string and sent to the command directly. Similarly, you can add output and/or err properties to capture the command's standard output and standard error (documentation here).

Categories : Javascript

To redirect output to log file and also accept user input in same batch script
If you want only certain parts of your script to be logged, just use >> SQL_LOGS.txt on those specific lines in your script (rather than using it on your call to the script). As for prompting the user for a specific response, give this article a quick read: http://www.quepublishing.com/articles/article.aspx?p=1154761&seqNum=12 EDIT - here's a batch script inspired by the above link that should help exemplify your goal. @echo off echo This is an example of accepting user input and writing some output to a log. :again set /p answer=Do you want to run a sql script (Y/N)? if /i "%answer:~,1%" EQU "Y" goto logit if /i "%answer:~,1%" EQU "N" exit /b echo Please type Y for Yes or N for No goto again :logit echo sql script goes here. this command's response is sent to th

Categories : Batch File

Run python file within python script, passing arguments
I would try doing somehting like this. os.system("appcfg.py arg1 arg2 arg3") I would look into this portion of the os documentation. Goodluck.

Categories : Python



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