python sys.argv has unexpected output - python

when i try using sys.argv after drag and drop files into program the output is unexpected
import time
import sys
time.sleep(3)
print(str(sys.argv))
output:
['C:\\Users\\lenovo\\Desktop\\py.py']C:\Users\lenovo\Desktop\yep.pyC:\Users\lenovo\Desktop\1.mp4.00_48_57_11.Still008.psd
expected output:
['C:\\Users\\lenovo\\Desktop\\py.py','C:\Users\lenovo\Desktop\yep.py','C:\Users\lenovo\Desktop\1.mp4.00_48_57_11.Still008.psd']

If I create a program test.py on my windows system (where .py files are associated with some python interpreter)
import time
import sys
print(str(sys.argv))
time.sleep(10)
Then using the filemanager I multi-select 2 files and drag/drop them on test.py, I get:
[
'D:\\temp\\StackOverflow\\test.py',
'D:\\temp\\StackOverflow\\in.csv',
'D:\\temp\\StackOverflow\\in.txt'
]
Is this not what you see?

Related

Running python program with arguments from another program

I want to call a python program from current program,
def multiply(a):
return a*5
mul = sys.argv[1]
I saved this file as test.py.so from the current file I'm calling it but i want to run the code in parallel like multiprocessing queue,But its not working.
what I tried so far,
import os
import sys
import numpy as np
cwd = os.getcwd()
l = [20,5,12,24]
for i in np.arange(len(l)):
os.system('python test.py multiply[i]')
I want to run the main script for all list items parallelly like multiprocessing. How to achieve that?
If you want to make your program work like that using that the os.system, you need to change the test.py file a bit:
import sys
def multiply(a):
return a*5
n = int(sys.argv[1])
print(multiply(n))
This code written like this takes the second element (the first one is just the name of the file) of argv that it took when you executed it with os.system and converted it to an integer, then executed your function (multiply by 5).
In these cases though, it's way better to just import this file as a module in your project.

Is there a way to import a variable in python without looping code?

I have looked at multiple different questions and answers but nothing I have looked at is helping me in the slightest. I am using Python 3 for all of this.
I am having a bit of trouble using python to transfer a variable to be used in a command-line prompt through python code. I am using os.system, and would prefer to use this, to execute a second python file, in the same folder.
The opening through command prompt works after a bit of testing, but when I try to import a variable from the first python code, it loops through the entire first bit of code.
My first python code is as follows:
import os
variable_to_transfer=input()
os.system('cmd /c "python file2.py"')
My second python code is as follows:
import os
from file1.py import variable_to_transfer
command='cmd /k "ping {0}"'.format(variable_to_transfer)
os.system(command)
When I run this set of code it runs through the first code once, goes to the second code and doesn't do anything at the line
from file1.py import variable_to_transfer
I intend for my codes to transfer the variable but it just loops. Any way to fix this?
It loops because your file1 is calling your file2 which imports from your file1 and recall your file2, etc. over and over. What you should do instead, is pass the variable as an argument and retrieve it from there. For example:
# file1.py
import os
variable_to_transfer=input()
os.system('cmd /c "python file2.py %s"' % variable_to_transfer)
# file2.py
import os
import sys
command='cmd /k "ping {0}"'.format(sys.argv[1])
os.system(command)

Run python file inside another

I am using python 3.5
I want to run a python script calling from another python script.
In particular, say I have script A (in particular, this is the exact file that I want to run: script A file):
Script A is the following.
if __name__ == '__main__':
args = argparser.parse_args()
_main(args)
I am running script B, inside script B, it calls script A.
How do I simply do this by calling the main function of script A while running script B?
Please no os.system('python scriptA.py 1'), this is not what i want. thanks
normally you can import it and call the main function
like
import script_a
...
script_a._main()
of course it could be that the script_a is not in you src structure, so that you can not simple import, or script_a is completely somewhere else.
Suppose the path of the script_a is path_a
you can
import sys
sys.path.append(path_a)
import script_a
script_a._main()
if you want to pass the args to script_a , in your script_b
import script_a
...
if __name__ == '__main__':
args = argparser.parse_args()
script_a._main(args)
In Script B simply import Script A,
import script_A
or
from script_A import *
now you can access your script A in script B
Treat the file like a module and put import scriptA at the top of your file.
You can then use scriptA.main(1) where 1 is the argument you are passing to it.
N.B When importing do not put .py at the end.
If you have code which is not indented inside of script A and if you import script A inside script B, it will automatically first run script A and then move on to the __main__() of script B. How ever if you wish control when the execution of script A begins, then , indent your code in Script A or code it in a normal function such as def start() .
Now, import Script A into Script B as follows
import ScriptA
And run the script A as
ScriptA.start()
NOTE: Make sure that script A and script B are in the same directory for this to work. Hope this solves your purpose. Cheers!

running python function with arguments from cmd.exe

I have Python function that takes 1 arguments
def build_ibs(Nthreads,LibCfg): # Nthreads is int,LibCfg as string
import os # module os must be imported
import subprocess
import sys
I use following in cmd.exe(on Win7) to call it
C:>cd C:\SVN\Python Code
C:\SVN\Python Code>C:\Python27\python.exe build_libs(4,'Release')
that throws error
using following
C:>cd C:\SVN\Python Code
C:\SVN\Python Code>C:\Python27\python.exe 4 'Release' # dosn't work
C:\SVN\Python Code>C:\Python27\python.exe 4 Release # dosn't work
does nothing, and no error is displayed even.
What is the correct way to call it both in cmd.exe or even Python shell command line?
Thanks
sedy
You can't just call a function from the command line - it must be inside a file. When you type python filename.py at the command line, what it does is feed the contents of filename.py into the Python interpreter with the namespace set to __main__.
So when you type Python.exe 4 'Release' it tries to find a file named 4. Since this file does not exist, Windows returns an Errno 2 - File not found.
Instead, put your code into a file - lets say test.py:
test.py:
def build_libs(Nthreads,LibCfg): # Nthreads is int,LibCfg as string
import os # module os must be imported
import subprocess
import sys
# ...
if __name__=='__main__':
numthreads = sys.argv[1] # first argument to script - 4
libconfig = sys.argv[2] # second argument
# call build_libs however you planned
build_libs(numthreads, libconfig)
Then run from the command line:
C:\Python27\python.exe test.py 4 Release
In the directory that test.py is saved in.
Update: If you need to use build_libs in multiple files, it's best to define it in a module, and then import it. For example:
mod_libs/__init__.py - empty file
mod_libs/core.py:
def build_libs(...):
....
# function definition goes here
test.py:
import sys
import mod_libs
if __name__ == '__main__':
mod_libs.build_libs(sys.argv[1], sys.argv[2])
If you want to use Python code as in your first attempt, you need to start the Python interpreter.
If you want to call a Python function from your OS's command line as in your second attempt, you need to use the proper modules (like sys.argv or argparse).
For example:
C:\SVN\Python Code> py
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import build_libs
>>> build_libs.build_libs(4, 'Release')
Or, in your build_libs.py, import the sys module at the top of the script, and then run the function based on its arguments at the end of the script:
import sys
...
print(build_libs(int(sys.argv[1]), sys.argv[2]))
Then at your OS's command line:
C:\SVN\Python Code> py build_libs 4 Release

Python, code works in the command line, but not when trying to create a program, please

... could someone explain the difference?
What I type in the command prompt:
sys.path.append('M:/PythonMods')
import qrcode
myqr = qrcode.make("randomtexxxxxxxxxt")
myqr.show()
myqr.save("M:/myqr.png")
MAKES A QR FOR THE TEXT.
The code I type:
sys.path.append('M:/PythonMods')
import scipy
from qrcode import myqr
file=open('myqr3.png',"r")
myqr.show()
file.close()
It doesn't recognise sys, do I need to import something? How come it runs in the command prompt?
Thanks in advance for any help.
add at the begining of your source file:
import sys
and while we're reviewing your code, in executable source files it is advised to do so:
import sys
sys.path.append('M:/PythonMods')
import qrcode
if __name__ == "__main__":
myqr = qrcode.make("randomtexxxxxxxxxt")
myqr.show()
myqr.save("M:/myqr.png")
so your code will run only when you execute it as a file, not when you import it. You may want to define your three lines as a function, and call your function in the if __name__ == "__main__": part, to be able to reuse it like any library!
At the top of the script, please include the following line:
import sys
sys is not a built-in, you do need to explicitly import it:
import sys
The ipython interactive shell imports a lot of modules by default; perhaps you are using that to test your code. The default Python runtime does not import sys for you.

Categories