User-defined command line arguments in python - python

Encountered a couple of problems with my python program. Basically, I want to be able to send the path files of multiple images to the command prompt (the user defines how many images, so just putting the direct file paths as args, as below, doesn't do what I want). My code currently looks like this:
os.system("java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar image_00000001.jpg image_00000002.jpg image_00000003.jpg")
There are many more images, so of course, writing out image_00000004, 5, 6, etc, is hardly efficient and depends entirely on there being the same number of images each time, which there isn't. (jpivc.jar is the program that opens upon execution of this code, and imports the images and does stuff - that bit works fine). Ideally, the code would be something like:
for i in range(1, NumberOfImages):
os.system("java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar image_0000000" + i + ".jpg")
Except, you know, without opening jpivc.jar each time i is incremented, I'm just using the above to show the kind of thing I want. Unfortunately this doesn't work, as it only sends the first part in " " to the command line, if it doesn't give an error message - my first question is, is there any way of making this do what I want it to do? I'm relatively inexperienced at python, so please be as gentle as possible with the technical details.
My second question is - is there a way of then closing either the command prompt or jpivc.jar? I've tried all the predefined functions I can think of - os.system("tskill cmd.exe") and variatons thereupon, os.kill() (although I'm using 2.5, so I'm not surprised this doesn't work), Popen.kill() and Popen.terminate(), and even tried writing my own kill function using ctypes. Nothing works - until either cmd.exe or jpivc.jar are closed manually, then everything in the rest of my code works perfectly. I think Python halts until the command line is closed - which isn't helpful when I want to then close the command line from Python! To sum up; why does it halt like that, and how can I fix it?
More extracts from my code can be provided if needed - I'm using Python 2.5.4 on Windows XP Professional. Don't ask me to provide anything from jpivc.jar - I won't even pretend to understand the slightest bit of Java.
Thanks in advance,
Dave

I believe you are looking for something like this
fileNames=""
for i in range(1, NumberOfImages):
fileNames += "image_0000000%d.jpg "%i
os.system( "java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar %s"%fileNames )
Rename your file from script.py to script.pyw to avoid the opening of command prompt.
jpivc.jar will remain open until you close it manually or programmer changes its code to quit after it completes processing all files.
[EDIT]
I found this for starting and killing a process
pidId = os.spawnl(os.P_NOWAIT, "\\windows\\notepad.exe")
import win32api
win32api.TerminateProcess(pidId ,0)

Related

How do I call a function in vs code using python?

I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.

Running python script through PHP script not working

So basically, I am trying to run some preliminary tests for a website I will be building.
There will be downloads through the site, possibly for the same resource by different users, possibly nearly or at the same time. I want to implement a lock manager of sorts to prevent repeated downloads of a resource when one is already in progress.
The test I am running is just to see if this is even possible. What I am specifically testing for right now is if I begin running a program, if I attempted to open the program again would it open a completely new instance or go to the already open instance. I am doing to this to try and see if user 1 makes changes in their program, if the second user opens their program, they will see those change; otherwise they might not see the changes if they open up a completely new instance of a program.
PHP
exec(escapeshellcmd("C:\Program Files\Python 3.7\python.exe Test2Php.py 0 Testing"), $o1, $r);
echo $r;
var_dump($o1);
Python
#!/usr/bin/env python
import sys
arr = []
t = sys.argv[1]
if (t == '0'):
arr = [sys.argv[k] for k in range(2, len(sys.argv))]
print("if")
else:
print(str(len(arr)))
The problem is the script doesn't return any output at all! It doesn't run either. I tested this by having the python program write a file at the end of successful execution. I have tried shell_exec, passthru, etc. The program itself works when run through command line, but not in any scripts I have made.
I am using a WAMP server on windows.
EDIT:
For anyone else dealing with this. Make sure you have the default Python package in your system path variable. You can do this easily by installing the latest version of python and choosing add to system path. Uninstall anaconda or whatever else may be in the way of the system path and enjoy.
Also make sure you find where the python exe is and use the full path to it.
Your list comprehension will get out of range since you can never do lst[len(lst)] without getting an IndexError. The str() wrapper isn't necessary to print len(arr).
Instead, use a slice of [:2] to remove the first 2 elements:
#!/usr/bin/env python
import sys
arr = []
t = sys.argv[1]
if t == '0':
arr = sys.argv[2:]
print("if")
else:
print(len(arr))

Python break the command line, why?

I just want to launch my program written in C++ from a Python script.
I wrote the following script:
import subprocess
subprocess.call(['l:\Proj\Silium.exe', '--AddWatch c:\fff.txt'])
But to my c++ application the parameter "--AddWatch c:\fff.txt" arrives without hyphens - it arrives as "AddWatch c:\fff.txt". So my program doesn't work.
Why does this happen, and how can I fix it?
UPD: thx for comments - yours answer helps!
I explain the issue and the solution.
I need to launch my application in the following way:
l:\Proj\Silium.exe --AddWatch c:\fff.txt
When I tried to do this using some hint from internet:
import subprocess
subprocess.call(['l:\Proj\Silium.exe', '--AddWatch c:\fff.txt'])
the key "--AddWatch" arrives to my program without hyphens - like "AddWatch".
The solution is quite simple:
import subprocess
subprocess.call(['l:\Proj\Silium.exe', '--AddCMakeWatch', 'c:\fff.txt',])
And issue gone away.
P.S.: its very strange that my initial code didnt work, I dont have any idea why python corrupt the command line, I think it is the python bug.

How do I give additional arguments when using Python to open on application on Mac?

I'm playing around with Flightgear and I'd like a way to launch /Applications/FlightGear.app from a Python script with a specific aircraft, but it's not accepting additional parameters.
This works:
os.system("open /Applications/FlightGear.app/Contents/MacOS/fgfs")
This does, but does not select the aircraft... I've tried both with and without hyphens in front of 'aircraft'.
os.system("open /Applications/FlightGear.app/Contents/MacOS/fgfs --args aircraft=777-200ER")
For references,
(source: flightgear.org)
Something like this. Sometimes some of the arguments will have to be combined, depending on their relation to each other.
import subprocess
p = subprocess.Popen(['open', '/Applications/FlightGear.app/Contents/MacOS/fgfs', '--args', 'aircraft=777-200ER'])
if p.wait() != 0:
raise EnvironmentError()
This is basic information that could've been found simply by searching "python run command" in Google. SO isn't just a tool for the lazy.
On OS X, open is to run an application. To run a command-line program you would just do it like on unix/linux, assuming that /Applications/FlightGear.app/Contents/MacOS/fgfs is actually a runnable program.
I can't test it for this particular case, but I think you want os.system() to run exactly what you would type at the command-line prompt. Hence,
os.system("/Applications/FlightGear.app/Contents/MacOS/fgfs --aircraft=777-200ER")

How do I take the output of one program and use it as the input of another?

I've looked at this and it wasn't much help.
I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?
Thanks for your help.
EDIT
Thanks to the guys that mentioned piping. I haven't used it too much and was glad it was brought up since it forced me too look in to it more.
p = subprocess.Popen(['ruby', 'ruby_program.rb'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
ruby_question = p.stdout.readline()
answer = calculate_answer(ruby_question)
p.stdin.write(answer)
print p.communicate()[0] # prints further info ruby may show.
The last 2 lines could be made into one:
print p.communicate(answer)[0]
If you're on unix / linux you can use piping:
question.rb | answer.py
Then the output of question.rb becomes the input of answer.py
I've not tried it recently, but I have a feeling the same syntax might work on Windows as well.
Pexpect
http://www.noah.org/wiki/Pexpect
Pexpect is a pure Python expect-like
module. Pexpect makes Python a better
tool for controlling other
applications.
Pexpect is a pure Python module for
spawning child applications;
controlling them; and responding to
expected patterns in their output.
Pexpect works like Don Libes' Expect.
Pexpect allows your script to spawn a
child application and control it as if
a human were typing commands.
First of all check this out:
[Unix piping][1]
It works on windows or unix but it's slighly dufferent, first the programs:
question.rb:
puts "This is the question"
answer.rb:
question = gets
#calculate answer
puts "This is the answer"
Then the command line:
In unix:
question.rb | answer.rb
In windows:
ruby question.rb | ruby answer.rb
Output:
This is the question
This is the answer
There are two ways (off the top of my head) to do this. The simplest if you're in a Unix environment is to use piping. Simple example:
cat .profile .shrc | more
This will send the output of the first command (cat .profile .shrc) to the more command using the pipe character |.
The second way is to call one program from the other in your source code. I'm don't know how Ruby handles this, but in Python you can run a program and get it's output by using the popen function. See this example chapter from Learning Python, then Ctrl-F for "popen" for some example code.

Categories