I have file loadMe.txt that i want to use in my script main.py. To do so I execute script from command line by command:
python main.py < loadMe.txt
How can I access to this loadMe.txt in my script in this "<" way? Also how operator "<" is named?
< is called "input redirection". It uses the file as an input source. You can think of cmd < file as equivalent to cat file | cmd.
In Python, there are a variety of ways to read from it. A basic input() command will read until a new line. You can also do something like this:
import sys
# use `sys.stdin` like the file.
whole_contents = sys.stdin.read()
# Or something like
first_five_chars = sys.stdin.read(5)
Related
I have a simple shell script script.sh:
echo "ubuntu:$1" | sudo chpasswd
I need to open the script, read it, insert the argument, and save it as a string like so: 'echo "ubuntu:arg_passed_when_opening" | sudo chpasswd' using Python.
All the options suggested here actually execute the script, which is not what I want.
Any suggestions?
You would do this the same way that you read any text file, and we can use sys.argv to get the argument passed when running the python script.
Ex:
import sys
with open('script.sh', 'r') as sfile:
modified_file_contents = sfile.read().replace('$1', sys.argv[1])
With this method, modified_file_contents is a string containing the text of the file, but with the specified variable replaced with the argument passed to the python script when it was run.
I'm trying to schedule a python script to run automatically on a Windows 10 machine. The script, when run alone, prompts the user for some input to use as it runs. I'd like to automatically set these inputs when the scheduler runs the .bat file. As an example:
test.py:
def main():
name = input('What is your name? ')
print(f'Hello, {name}. How are you today?')
main()
This works fine if I just run the script, but ideally I'd like to have the name variable passed to it from the .bat file.
test.bat:
"path\to\python.exe" "path\to\test.py"
pause
Any help would be greatly appreciated!
If you just want to give a single fixed input, you can do it like:
REM If you add extra spaces before `|` those will be passed to the program
ECHO name_for_python| "path\to\python.exe" "path\to\test.py"
Unfortunately, there is no good way of extending this to multiple lines. You would use a file containing the lines you want to input for that:
"path\to\python.exe" "path\to\test.py" < file_with_inputs.txt
If you want to have everything into a standalone script, you may do something like this:
REM Choose some path for a temporary file
SET temp_file=%TEMP%\input_for_my_script
REM Write input lines to file, use > for first line to make sure file is cleared
ECHO input line 1> %temp_file%
REM Use >> for remaining lines to append to file
ECHO input line 2>> %temp_file%
ECHO input line 3>> %temp_file%
REM Call program with input file
"path\to\python.exe" "path\to\test.py" < file_with_inputs.txt
REM Delete the temporary file
DEL %temp_file% /q
Obviously, this is assuming you cannot use the standard sys.argv (or extensions like argparse), which would be the more standard and convenient way to send arguments to a script.
How can I run a text file use Python?
For example; if the text file is called textfile.txt, and it contains the line:
print("Hello")
How can I use Python to run this as lines of code?
You can use exec: https://docs.python.org/3/library/functions.html#exec
so your code would look somehow like this:
filehandle = open("filename.txt","r")
code_to_execute = filehandle.read()
exec(code_to_execute)
remeber that your file has to have correct syntax so no syntax error occours (mostly its about indentation)
Simply call the python interpreter and pass it the file as such:
python yourfile.txt
I have a program that takes an input file:
python subprogram.py < input.txt > out.txt
If I have a number of input files, how can I write a single python program runs on those inputs and produces a single output? I believe the program should run like:
python program.py < input_1.txt input_2.txt > out.txt
And the program itself should look something like:
from subprogram import MyClass
import sys
if __name__ == '__main__':
myclass = MyClass()
myclass.run()
Have a look at the fileinput module
import fileinput
for line in fileinput.input():
process(line)
This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.
Make your program accept command line parameters:
python program.py input_1.txt input_2.txt > out.txt
And you can access them like:
from subprogram import MyClass
import sys
if __name__ == '__main__':
class = MyClass()
class.run(sys.argv)
The way you're using is not about Python, it's about your shell. You are just redirect standart input/output to files. If you want to achieve that:
cat input1.txt input2.txt | python subprogram.py > out.txt
Let your shell do the work for you:
cat input_1.txt input_2.txt | python program.py > out.text
The cat command will concatenate the two input files together and your python program can just read from stdin and treat them like one big file.
In the Linux kernel, I can send a file to the printer using the following command
cat file.txt > /dev/usb/lp0
From what I understand, this redirects the contents in file.txt into the printing location. I tried using the following command
>>os.system('cat file.txt > /dev/usb/lp0')
I thought this command would achieve the same thing, but it gave me a "Permission Denied" error. In the command line, I would run the following command prior to concatenating.
sudo chown root:lpadmin /dev/usb/lp0
Is there a better way to do this?
While there's no reason your code shouldn't work, this probably isn't the way you want to do this. If you just want to run shell commands, bash is much better than python. On the other hand, if you want to use Python, there are better ways to copy files than shell redirection.
The simplest way to copy one file to another is to use shutil:
shutil.copyfile('file.txt', '/dev/usb/lp0')
(Of course if you have permissions problems that prevent redirect from working, you'll have the same permissions problems with copying.)
You want a program that reads input from the keyboard, and when it gets a certain input, it prints a certain file. That's easy:
import shutil
while True:
line = raw_input() # or just input() if you're on Python 3.x
if line == 'certain input':
shutil.copyfile('file.txt', '/dev/usb/lp0')
Obviously a real program will be a bit more complex—it'll do different things with different commands, and maybe take arguments that tell it which file to print, and so on. If you want to go that way, the cmd module is a great help.
Remember, in UNIX - everything is a file. Even devices.
So, you can just use basic (or anything else, e.g. shutil.copyfile) files methods (http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files).
In your case code may (just a way) be like that:
# Read file.txt
with open('file.txt', 'r') as content_file:
content = content_file.read()
with open('/dev/usb/lp0', 'w') as target_device:
target_device.write(content)
P. S. Please, don't use system() call (or similar) to solve your issue.
under windows OS there is no cat command you should usetype instead of cat under windows
(**if you want to run cat command under windows please look at: https://stackoverflow.com/a/71998867/2723298 )
import os
os.system('type a.txt > copy.txt')
..or if your OS is linux and cat command didn't work anyway here are other methods to copy file..
with grep:
import os
os.system('grep "" a.txt > b.txt')
*' ' are important!
copy file with sed:
os.system('sed "" a.txt > sed.txt')
copy file with awk:
os.system('awk "{print $0}" a.txt > awk.txt')