w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
unable to access variable declared in ksh script to csh script using shell script
The ksh script is not doing what you think it is doing when used by ksh; it sets $1 first to MyUser=root and then MyPassword=shroot. However, when you source it from your C shell script, because the syntax is compatible with C shell (checked with tcsh), you would set the two variables. If you sourced the script from a Bourne-shell derivative, the exit at the end of the ksh script would cause the shell to exit; it does not seem to cause the C shell to exit. So, what you've got is a weird hybrid. Normally, you stick to one language and use it exclusively. Where you need to use another shell, you can do so, but you simply run the script written for the other shell. You can communicate to the other script with environment variables. You don't normally try writing sourceable code that ca

Categories : Shell

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 modify all text files in folder with Python Script
Easy: you don't have to specify a filename. fileinput will take the filenams from sys.argv by default. You don't even have to use enumerate, as fileinput numbers the lines in each file: import sys, fileinput for line in fileinput.input(inplace=True): sys.stdout.write(line.replace('sit', 'SIT')) if fileinput.filelineno() == 30: sys.stdout.write('TextToInsertIntoLine32' ' ')

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

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 access ant variables in python script
I believe you can use a single properties file (e.g. build.py) that's read by Ant and Python. For example: build.xml <project default="build"> <property file="build.py"/> <target name="build"> <echo message="${src.webinf}"/> </target> </project> script.py #!/usr/bin/python import ConfigParser config = ConfigParser.ConfigParser() config.read("build.py") print config.get("properties", "src.webinf") build.py [properties] src.webinf = WEB-INF Example usage $ ant Buildfile: /Applications/MAMP/htdocs/clicks/test/build.xml build: [echo] WEB-INF BUILD SUCCESSFUL Total time: 0 seconds $ python script.py WEB-INF

Categories : Ant

How do I access the URL's Query String in a Python CGI script?
First of all, the 'self' keyword is only available once defined in a function, typically an object's. It is normally used the same way 'this' is used in other OOP languages. Now, the snippet of code you were trying to use was intended for the Google App Engine, which you have not imported (nor installed, I presume). Since you are accustomed to using environment variables, here's what you can do: #!/usr/bin/python import os print os.environ.get("QUERY_STRING", "No Query String in url") However, I would advise you to use the cgi module instead. Read more about it here: http://docs.python.org/2/library/cgi.html

Categories : Python

Get rows when trying to access columns in a python script
The problem is probably your data. Verify that the CSV data is read correctly (debug the reader). When I run your script with the following input files: file1.csv foo,bar,baz 1,2,3 2,3,4 3,4,5 file2.csv 4,5,6 5,6,7 6,7,8 Then the result of your script is the following: $ python test.py [['4' '5'] ['5' '6'] ['6' '7'] ['foo' 'bar'] ['1' '2'] ['2' '3'] ['3' '4']] Therefore I think your bug must be about reading the CSV files. Maybe the column separator isn't working correctly.

Categories : Python

python : access namespace of called script
You can't access this. By the time you have arrived in the last line of your script, the called script has finished executing. Therefore its variables don't exist any more. You need to send this data to the calling script in some other way (such as the called script printing it on the standard output and the calling script getting it from there). Even if it hadn't finished executing, I don't think you could access its variables. In other words, your impression is wrong :-)

Categories : Python

Access session variable that is set in Script 1, in Script 2. PHP
PHP session changes aren't written to the session storage by default until the end of the program; while the program is running, $_SESSION is just like any other variable; only accessible within its own program; it's only when the program ends and the session is written to disk that the next program can get at the changes you've made to the session data. So the short answer is that you won't be able to do this just by checking the session and expecting the latest updates to be there. You can force PHP to write to the session at any time during the program by using the session_write_close() function, but as you may gather from the function name, this will also close the session to that program, so that program can't make any further updates to it. I guess you could then re-open the sessio

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

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

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

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

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

Modify script from another script
This is a possible approach - using a condition that is set in the main program to decide whether to execute a particular line in the script. If your main program is for ii = 1:9 skipLine3 = (mod(ii,3)==0); runSub end And runSub.m looks like this: A = 1; B = 2; % modified lines to trap condition where 'skipLine3' doesn't exist: if ~exist('skipLine3', 'var') skipMe = false; else skipMe = skipLine3; end if ~skipMe, B=B*2; end fprintf(1, "for iteration %d B is %d ", ii, B) Then the output will be: for iteration 1 B is 4 for iteration 2 B is 4 for iteration 3 B is 2 for iteration 4 B is 4 for iteration 5 B is 4 for iteration 6 B is 2 for iteration 7 B is 4 for iteration 8 B is 4 for iteration 9 B is 2 As you can see - the skipLine3 parameter, which is set in the main loop (every

Categories : Matlab

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

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

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

How do I properly use python to access system commands and make my script work?
You forgot , in all subprocess.call([...]) ["i3-msg", "-t", "get_workspaces"] edit: if len(status_list) <=3: subprocess.check_output(["dzconky_for_3_workspaces.sh"]) else: subprocess.check_output(["dzconky.sh"]) dzconky_for_3_workspaces.sh #!/bin/sh exec conky -d -c "$HOME/bin/conkyrc_cli" | dzen2 -fg "#666666" -bg "#333333" -ta left -w 725 -x 54 -y 750 & exit 0

Categories : Python

How to create python test script to access services hosted in GAE which require login
Ok I think this might be what you are looking for, client libraries to authenticate and yeah I believe appengine now recommends using the oauth2 for any kind of authentication: https://developers.google.com/accounts/docs/OAuth2#libraries Then you get an auth token where you pass in headers on your restful request like: # Your authenticated request Authorization: Bearer TokenHere Then in your handler you get it like: try: user = oauth.get_current_user('https://www.googleapis.com/auth/userinfo') except NotAllowedError: user = None # then from the first link you should be able to access if user.is_current_user_admin() This is how I authenticate on android, but I only do this once and store it in session and just enable cookie jar on the httpclient.

Categories : Python

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

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

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

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

Modify CSV via Script
maybe you are looking for CSVfix, this is a tool for manipulating CSV data in the command shell. Take a look here: https://code.google.com/p/csvfix/ With it you can, among other things: Reorder, remove, split and merge fields Convert case, trim leading & trailing spaces Search for specific content using regular expressions Filter out duplicate data or data on exclusion lists Enrich with data from other sources Add sequence numbers and file source information Split large CSV files into smaller files based on field contents Perform arithmetic calculations on individual fields Validate CSV data against a collection of validation rules and convert between CSV and fixed format, XML, SQL and DSV I hope this helps you out, best regards, Jürgen Jester

Categories : Csv

Google Apps Script Spreadsheets - Assign script to image from a script
This would be a cool feature, but here is a possible workaround, it might even offer more functionality. You can build a UI using Google API. More detailes here. The UI allows you to create side bars/menus/etc. You could even create floating dialog windows. Using AbsolutePanel, you can even choose where the dialogue shows up.

Categories : Google Apps Script

Powershell start-process script calls a second script - how to make one script only
Windows does not allow a process to elevate while running. There are some tricks but in one way or another they will spawn a new process with the elevated rights. See here for more info. So the easiest way for PowerShell is still using one script to Start-Process the other script elevated.

Categories : Powershell

calling python script from another script
you need to give it the full path to the script that you are trying to call, if you want to do this dynamically (and you're in the same directory), you can do: import os full_path = os.path.abspath('kvadrat.py')

Categories : Python

run script inside a script by python
Source call is good with simple intepreting languages, python has namespaces and imports, so why not use it. A good practice is to use such a scheme: # example.py def main(): main logic here... if __name__ == "__main__": main() This allows you to run the script from a command line (the if name part), or just import the script in another script and run main(), i.e. import example example.main()

Categories : Python

How to call a *.jsl script from python script
You should take a look at the JMP automation guide. You can automate JMP from Python using the win32com interface, which is unfortunately quite buggy and incomplete. I've written a custom library of code to work around these issues, largely because my job requires me to work with JMP extensively and its built-in jsl programming language is awful at many things.

Categories : Python

Python code works okay via terminal, but not via wsgi script. ( TypeError: 'NoneType' object is not iterable )
WSGI requires that you return the output you want to send back to a browser as the return value of your function, not just print it out. So you'd need to use pprint.pformat() and return its result, rather than pprint.pprint (which just tries to print it out via print - not what you want here). def application(environ, start_response): start_response('200 OK', [('content-type', 'text/html')]) aaa = ['a','b','c'] return pprint.pformat(aaa)

Categories : Python

Modify CSV header using bash script
Yes, it's a sed one-liner: sed -i -r '1{s/(^|$)/"/g;s/,/","/g}' file.csv This means: -i - edit files in place -r - use extended regular expressions 1{...} - perform the operations in {...} only on the first line of the file s/(^|$)/"/g - replace (s) either the beginning (^) or end ($) of the line with ", everywhere they occur (g), then s/,/","/g - replace (s) each instance of , with "," everywhere it occurs (g)

Categories : Bash

shell script: replace the contents
try this: (save it to your main.sh): #!/bin/ksh awk -F: -v a="$1" -v i="$2" 'NR==1{n=$2;print $1":"a"-"i;next}{print $1":"n}' /VersionInfo.properties > /tmp/tmpVersion && mv /tmp/tmpVersion VersionInfo.properties try with main.sh "13.7.0" "4"

Categories : Shell

Include file contents in script PHP
You cannot treat a part of a file like you wish to. You can use heredoc syntax for now, like this : $data = <<<END ... END; Later you replace this code by : $data = file_get_contents ( $filename );

Categories : PHP

change contents of one script using another in javascript
You can do something like this: var code = "javascript:go('http://www.adworkmedia.com/go.php?camp=4556&pub=24043&id=10694&sid=', 'trials'); return false;" $('.Tips4').attr('onclick', code);

Categories : Javascript



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